void PlaylistView::paintEvent(QPaintEvent* event) { // Reimplemented to draw the background image. // Reimplemented also to draw the drop indicator // When the user is dragging some stuff over the playlist paintEvent gets // called for the entire viewport every time the user moves the mouse. // The drawTree is kinda expensive, so we cache the result and draw from the // cache while the user is dragging. The cached pixmap gets invalidated in // dragLeaveEvent, dropEvent and scrollContentsBy. // Draw background if (background_image_type_ == Custom || background_image_type_ == AlbumCover) { if (!background_image_.isNull() || !previous_background_image_.isNull()) { QPainter background_painter(viewport()); // Check if we should recompute the background image if (height() != last_height_ || width() != last_width_ || force_background_redraw_) { if (background_image_.isNull()) { cached_scaled_background_image_ = QPixmap(); } else { cached_scaled_background_image_ = QPixmap::fromImage(background_image_.scaled( width(), height(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation)); } last_height_ = height(); last_width_ = width(); force_background_redraw_ = false; } // Actually draw the background image if (!cached_scaled_background_image_.isNull()) { // Set opactiy only if needed, as this deactivate hardware acceleration if (!qFuzzyCompare(previous_background_image_opacity_, qreal(0.0))) { background_painter.setOpacity(1.0 - previous_background_image_opacity_); } background_painter.drawPixmap( (width() - cached_scaled_background_image_.width()) / 2, (height() - cached_scaled_background_image_.height()) / 2, cached_scaled_background_image_); } // Draw the previous background image if we're fading if (!previous_background_image_.isNull()) { background_painter.setOpacity(previous_background_image_opacity_); background_painter.drawPixmap( (width() - previous_background_image_.width()) / 2, (height() - previous_background_image_.height()) / 2, previous_background_image_); } } } QPainter p(viewport()); if (drop_indicator_row_ != -1) { if (cached_tree_.isNull()) { cached_tree_ = QPixmap(size()); cached_tree_.fill(Qt::transparent); QPainter cache_painter(&cached_tree_); drawTree(&cache_painter, event->region()); } p.drawPixmap(0, 0, cached_tree_); } else { drawTree(&p, event->region()); return; } const int first_column = header_->logicalIndex(0); // Find the y position of the drop indicator QModelIndex drop_index = model()->index(drop_indicator_row_, first_column); int drop_pos = -1; switch (dropIndicatorPosition()) { case QAbstractItemView::OnItem: return; // Don't draw anything case QAbstractItemView::AboveItem: drop_pos = visualRect(drop_index).top(); break; case QAbstractItemView::BelowItem: drop_pos = visualRect(drop_index).bottom() + 1; break; case QAbstractItemView::OnViewport: if (model()->rowCount() == 0) drop_pos = 1; else drop_pos = 1 + visualRect(model()->index(model()->rowCount() - 1, first_column)).bottom(); break; } // Draw a nice gradient first QColor line_color(QApplication::palette().color(QPalette::Highlight)); QColor shadow_color(line_color.lighter(140)); QColor shadow_fadeout_color(shadow_color); shadow_color.setAlpha(255); shadow_fadeout_color.setAlpha(0); QLinearGradient gradient(QPoint(0, drop_pos - kDropIndicatorGradientWidth), QPoint(0, drop_pos + kDropIndicatorGradientWidth)); gradient.setColorAt(0.0, shadow_fadeout_color); gradient.setColorAt(0.5, shadow_color); gradient.setColorAt(1.0, shadow_fadeout_color); QPen gradient_pen(QBrush(gradient), kDropIndicatorGradientWidth * 2); p.setPen(gradient_pen); p.drawLine(QPoint(0, drop_pos), QPoint(width(), drop_pos)); // Now draw the line on top QPen line_pen(line_color, kDropIndicatorWidth); p.setPen(line_pen); p.drawLine(QPoint(0, drop_pos), QPoint(width(), drop_pos)); }
void Nightcharts::draw(QPainter *painter) { painter->setRenderHint(QPainter::Antialiasing); painter->setPen(Qt::NoPen); if (ctype == Nightcharts::Pie) { pW = 0; double pdegree = 0; //Options QLinearGradient gradient(cX+0.5*cW, cY, cX+0.5*cW, cY+cH*2.5); gradient.setColorAt(1, Qt::black); //Draw //pdegree = (360/100)*pieces[i].pPerc; if (shadows) { double sumangle = 0; for (int i=0;i<pieces.size();i++) { sumangle += 3.6*pieces[i].pPerc; } painter->setBrush(Qt::darkGray); painter->drawPie(cX,cY+pW+5,cW,cH,palpha*16,sumangle*16); } QPen pen; pen.setWidth(2); for (int i = 0; i < pieces.size(); i++) { gradient.setColorAt(0,pieces[i].rgbColor); painter->setBrush(gradient); pen.setColor(pieces[i].rgbColor); painter->setPen(pen); pdegree = 3.6*pieces[i].pPerc; painter->drawPie(cX,cY,cW,cH,palpha*16,pdegree*16); palpha += pdegree; } } else if (ctype == Nightcharts::Dpie) { pW = 50; double pdegree = 0; QPointF p; QLinearGradient gradient(cX-0.5*cW, cY+cH/2, cX+1.5*cW, cY+cH/2); gradient.setColorAt(0, Qt::black); gradient.setColorAt(1, Qt::white); QLinearGradient gradient_side(cX, cY+cH, cX+cW, cY+cH); gradient_side.setColorAt(0,Qt::black); double sumangle = 0; for (int i = 0; i < pieces.size(); i++) { sumangle += 3.6*pieces[i].pPerc; } if (shadows) { painter->setBrush(Qt::darkGray); painter->drawPie(cX, cY+pW+5, cW, cH, palpha*16, sumangle*16); } int q = GetQuater(palpha+sumangle); if (q ==2 || q==3) { QPointF p = GetPoint(palpha+sumangle); QPointF points[4] = { QPointF(p.x(), p.y()), QPointF(p.x(), p.y()+pW), QPointF(cX+cW/2, cY+cH/2+pW), QPointF(cX+cW/2, cY+cH/2) }; gradient_side.setColorAt(1, pieces[pieces.size()-1].rgbColor); painter->setBrush(gradient_side); painter->drawPolygon(points, 4); } p = GetPoint(palpha); q = GetQuater(palpha); if (q ==1 || q==4) { QPointF points[4] = { QPointF(p.x(),p.y()), QPointF(p.x(),p.y()+pW), QPointF(cX+cW/2,cY+cH/2+pW), QPointF(cX+cW/2,cY+cH/2) }; gradient_side.setColorAt(1,pieces[0].rgbColor); painter->setBrush(gradient_side); painter->drawPolygon(points,4); } for (int i = 0; i < pieces.size(); i++) { gradient.setColorAt(0.5,pieces[i].rgbColor); painter->setBrush(gradient); pdegree = 3.6*pieces[i].pPerc; painter->drawPie(cX,cY,cW,cH,palpha*16,pdegree*16); double a_ = Angle360(palpha); int q_ = GetQuater(palpha); palpha += pdegree; double a = Angle360(palpha); int q = GetQuater(palpha); QPainterPath path; p = GetPoint(palpha); if((q == 3 || q == 4) && (q_ == 3 || q_ == 4)) { // 1) if (a>a_) { QPointF p_old = GetPoint(palpha-pdegree); path.moveTo(p_old.x()-1,p_old.y()); path.arcTo(cX,cY,cW,cH,palpha-pdegree,pdegree); path.lineTo(p.x(),p.y()+pW); path.arcTo(cX,cY+pW,cW,cH,palpha,-pdegree); } // 2) else { path.moveTo(cX,cY+cH/2); path.arcTo(cX,cY,cW,cH,180,Angle360(palpha)-180); path.lineTo(p.x(),p.y()+pW); path.arcTo(cX,cY+pW,cW,cH,Angle360(palpha),-Angle360(palpha)+180); path.lineTo(cX,cY+cH/2); path.moveTo(p.x(),p.y()); path.arcTo(cX,cY,cW,cH,palpha-pdegree,360-Angle360(palpha-pdegree)); path.lineTo(cX+cW,cY+cH/2+pW); path.arcTo(cX,cY+pW,cW,cH,0,-360+Angle360(palpha-pdegree)); } } // 3) else if((q == 3 || q == 4) && (q_ == 1 || q_ == 2) && a>a_ ) { path.moveTo(cX,cY+cH/2); path.arcTo(cX,cY,cW,cH,180,Angle360(palpha)-180); path.lineTo(p.x(),p.y()+pW); path.arcTo(cX,cY+pW,cW,cH,Angle360(palpha),-Angle360(palpha)+180); path.lineTo(cX,cY+cH/2); } // 4) else if((q == 1 || q == 2) && (q_ == 3 || q_ == 4) && a<a_) { p = GetPoint(palpha-pdegree); path.moveTo(p.x(),p.y()); path.arcTo(cX,cY,cW,cH,palpha-pdegree,360-Angle360(palpha-pdegree)); path.lineTo(cX+cW,cY+cH/2+pW); path.arcTo(cX,cY+pW,cW,cH,0,-360+Angle360(palpha-pdegree)); } // 5) else if((q ==1 || q==2) && (q_==1 || q_==2) && a<a_) { path.moveTo(cX,cY+cH/2); path.arcTo(cX,cY,cW,cH,180,180); path.lineTo(cX+cW,cY+cH/2+pW); path.arcTo(cX,cY+pW,cW,cH,0,-180); path.lineTo(cX,cY+cH/2); } if (!path.isEmpty()) { gradient_side.setColorAt(1,pieces[i].rgbColor); painter->setBrush(gradient_side); painter->drawPath(path); } } } else if (this->ctype==Nightcharts::Histogramm) { double pDist = 15; double pW = (cW-(pieces.size())*pDist)/pieces.size(); QLinearGradient gradient(cX+cW/2,cY,cX+cW/2,cY+cH); gradient.setColorAt(0,Qt::black); QPen pen; pen.setWidth(3); for (int i=0;i<pieces.size();i++) { if (shadows) { painter->setPen(Qt::NoPen); painter->setBrush(Qt::darkGray); painter->drawRect(cX+pDist+i*(pW + pDist)-pDist/2,cY+cH-1,pW,-cH/100*pieces[i].pPerc+pDist/2-5); } gradient.setColorAt(1,pieces[i].rgbColor); painter->setBrush(gradient); pen.setColor(pieces[i].rgbColor); painter->setPen(pen); painter->drawRect(cX+pDist+i*(pW + pDist),cY+cH,pW,-cH/100*pieces[i].pPerc-5); QString label = QString::number(pieces[i].pPerc)+"%"; painter->setPen(Qt::SolidLine); painter->drawText(cX+pDist+i*(pW + pDist)+pW/2-painter->fontMetrics().width(label)/2,cY+cH-cH/100*pieces[i].pPerc-painter->fontMetrics().height()/2,label); } painter->setPen(Qt::SolidLine); for (int i=1;i<10;i++) { painter->drawLine(cX-3,cY+cH/10*i,cX+3,cY+cH/10*i); } painter->drawLine(cX,cY+cH,cX,cY); painter->drawLine(cX,cY,cX+4,cY+10); painter->drawLine(cX,cY,cX-4,cY+10); painter->drawLine(cX,cY+cH,cX+cW,cY+cH); } }
void QScriptEdit::extraAreaPaintEvent(QPaintEvent *e) { QRect rect = e->rect(); QPalette pal = palette(); pal.setCurrentColorGroup(QPalette::Active); QPainter painter(m_extraArea); painter.fillRect(rect, Qt::lightGray); const QFontMetrics fm(fontMetrics()); int markWidth = fm.lineSpacing(); int extraAreaWidth = m_extraArea->width(); QLinearGradient gradient(QPointF(extraAreaWidth - 10, 0), QPointF(extraAreaWidth, 0)); gradient.setColorAt(0, pal.color(QPalette::Background)); gradient.setColorAt(1, pal.color(QPalette::Base)); painter.fillRect(rect, gradient); QLinearGradient gradient2(QPointF(0, 0), QPointF(markWidth, 0)); gradient2.setColorAt(0, pal.color(QPalette::Dark)); gradient2.setColorAt(1, pal.color(QPalette::Background)); painter.fillRect(rect.intersected(QRect(rect.x(), rect.y(), markWidth, rect.height())), gradient2); painter.setPen(QPen(pal.color(QPalette::Background), 2)); if (isLeftToRight()) painter.drawLine(rect.x() + extraAreaWidth-1, rect.top(), rect.x() + extraAreaWidth-1, rect.bottom()); else painter.drawLine(rect.x(), rect.top(), rect.x(), rect.bottom()); painter.setRenderHint(QPainter::Antialiasing); QTextBlock block = firstVisibleBlock(); int blockNumber = block.blockNumber(); qreal top = blockBoundingGeometry(block).translated(contentOffset()).top(); qreal bottom = top + blockBoundingRect(block).height(); QString imagesPath = QString::fromLatin1(":/qt/scripttools/debugging/images"); QString imageExt; // SVGs don't work on all platforms, even when QT_NO_SVG is not defined, so disable SVG usage for now. // #ifndef QT_NO_SVG #if 0 imageExt = QString::fromLatin1("svg"); #else imageExt = QString::fromLatin1("png"); #endif while (block.isValid() && top <= rect.bottom()) { if (block.isVisible() && bottom >= rect.top()) { int lineNumber = blockNumber + m_baseLineNumber; if (m_breakpoints.contains(lineNumber)) { int radius = fm.lineSpacing() - 1; QRect r(rect.x(), (int)top, radius, radius); QIcon icon(m_breakpoints[lineNumber].enabled ? QString::fromLatin1("%0/breakpoint.%1").arg(imagesPath).arg(imageExt) : QString::fromLatin1("%0/d_breakpoint.%1").arg(imagesPath).arg(imageExt)); icon.paint(&painter, r, Qt::AlignCenter); } if (m_executionLineNumber == lineNumber) { int radius = fm.lineSpacing() - 1; QRect r(rect.x(), (int)top, radius, radius); QIcon icon(QString::fromLatin1("%0/location.%1").arg(imagesPath).arg(imageExt)); icon.paint(&painter, r, Qt::AlignCenter); } if (!isExecutableLine(lineNumber)) painter.setPen(pal.color(QPalette::Mid)); else painter.setPen(QColor(Qt::darkCyan)); QString number = QString::number(lineNumber); painter.drawText(rect.x() + markWidth, (int)top, rect.x() + extraAreaWidth - markWidth - 4, fm.height(), Qt::AlignRight, number); } block = block.next(); top = bottom; bottom = top + blockBoundingRect(block).height(); ++blockNumber; } }
void Peg::setAppearance(const QColor& color) { QRadialGradient gradient(QPointF(10,10), 10, QPoint(10,13)); gradient.setColorAt(0, color); gradient.setColorAt(1, color.darker()); setBrush(gradient); }
// Modified Steepest Descent Minimiser bool FitKernel::sdModMinimise(Array<double>& alpha, double randomMin, double randomMax) { // Control variables double gradientDelta = 0.01; const int maxIterations = 100; const double factor = 0.50; Array<double> gradient(alpha.nItems()), tempAlpha(alpha.nItems()); double currentRMSE, deltaRMSE, lambda = 1.0; bool converged = false; int n, i; // Loop over whole routine (up to maxSteps) int step = 0; do { // Get initial cost from supplied alpha double oldRMSE = rmsError(alpha); msg.print("Initial RMSE = %e\n", oldRMSE); // Check for RMSE being less than current tolerance if (oldRMSE < tolerance_) { msg.print("Current RMSE (%e) is below tolerance value (%e) so no point continuing minimisation.\n", oldRMSE, tolerance_); break; } // Randomise initial parameters to try and find better initial set? if ((modSDNRandomTrials_ > 0) && (step < modSDNRandomTrials_)) { msg.print("Generating %i random values per alpha, within the range %e < alpha < %e.\n", modSDNRandomTrials_, randomMin, randomMax); for (n=0; n<alpha.nItems(); ++n) { tempAlpha = alpha; for (i=0; i<modSDNRandomTrials_; ++i) { tempAlpha[n] = UChromaMath::random() * (randomMax - randomMin) + randomMin; currentRMSE = rmsError(tempAlpha); if (currentRMSE < oldRMSE) { msg.print("Replaced current alpha with random parameters (deltaRMSE = %f).\n", currentRMSE - oldRMSE); oldRMSE = currentRMSE; alpha = tempAlpha; } } } } // Create initial gradient for (n=0; n<alpha.nItems(); ++n) { tempAlpha = alpha; tempAlpha[n] = (1.0+gradientDelta) * alpha[n]; gradient[n] = rmsError(tempAlpha); tempAlpha[n] = (1.0-gradientDelta) * alpha[n]; gradient[n] -= rmsError(tempAlpha); } gradient /= (2.0*gradientDelta); // Go! // Do some iterations do { ++step; // Setup scaling factors for alpha double maxGrad = fabs(gradient[n]); for (n=0; n<alpha.nItems(); ++n) if (fabs(gradient[n]) > maxGrad) maxGrad = fabs(gradient[n]); gradient /= maxGrad; for (n=0; n<alpha.nItems(); ++n) if (fabs(gradient[n]) < 0.01) gradient[n] = 0.0; bool reduced = false; double lastDeltaRMSE = 1.0; int nSwaps = 0; bool foundPoint = false; for (i=0; i<maxIterations; ++i) { if ((fabs(lambda) < 1.0e-4) && (deltaRMSE > 0.0)) { lambda = (lambda < 0.0 ? 1.0 : -1.0); if (++nSwaps > 2) break; } // Update alpha and get RMSE for (n=0; n<alpha.nItems(); ++n) tempAlpha[n] = alpha[n] - gradient[n]*lambda; currentRMSE = rmsError(tempAlpha); // Current RMSE higher than old RMSE? deltaRMSE = currentRMSE - oldRMSE; if (deltaRMSE > 0.0) { lambda *= factor; reduced = true; // printf(" -- %03i Reduce (deltaRMSE = %f), lambda = %f \n", i, deltaRMSE, lambda); } else if (!reduced) { // If we have made things worse, revert to the previous cost if (deltaRMSE > lastDeltaRMSE) { lambda *= factor; // printf(" -- %03i Worse delta (%f), so reverting to lambda = %f \n", i, deltaRMSE, lambda); foundPoint = true; break; } // First iteration, and we have reduced the RMSE, so double lambda and try again... lambda /= factor; lastDeltaRMSE = deltaRMSE; // printf(" -- %03i Incrse (deltaRMSE = %f), lambda = %f \n", i, deltaRMSE, lambda); } else { foundPoint = true; break; } } // Did we actually manage to reduce the RMSE? if (!foundPoint) { msg.print("Step %04i RMSE = %e (no better step found)\n", step, oldRMSE); break; } // Calculate new RMSE from current lambda for (n=0; n<alpha.nItems(); ++n) alpha[n] = alpha[n] - gradient[n]*lambda; currentRMSE = rmsError(alpha); deltaRMSE = currentRMSE - oldRMSE; // Check on convergence tolerance if (fabs(deltaRMSE) < tolerance_) { msg.print("Step %04i RMSE = %e (delta = %e) [CONVERGED, tolerance = %e]\n", step, currentRMSE, deltaRMSE, tolerance_); converged = true; break; } // Generate new gradient for (n=0; n<alpha.nItems(); ++n) { tempAlpha = alpha; tempAlpha[n] = (1.0+gradientDelta) * alpha[n]; gradient[n] = rmsError(tempAlpha); tempAlpha[n] = (1.0-gradientDelta) * alpha[n]; gradient[n] -= rmsError(tempAlpha); }; gradient /= (2.0*gradientDelta); oldRMSE = currentRMSE; msg.print("Step %04i RMSE = %e (delta = %e)\n", step, oldRMSE, deltaRMSE); } while (step < maxSteps_); // Check for convergence if (converged) break; } while (step < maxSteps_); // Get final cost msg.print("Final RMSE = %e\n", rmsError(alpha)); return true; }
void RangeLevelEditor::paintEvent(QPaintEvent *e) { if (!scale_1 || !scale_2 || !range_1 || !range_2) return; QPainter p(this); p.drawPixmap(0,0,skin.bg); p.setPen(skin.line_color); p.setClipRect(QRect(skin.border_w,skin.border_w,width()-skin.border_w*2,height()-skin.border_w*2)); for (int i=0;i<width();i++) { float from_x=(float)i/(float)width(); if (from_x<range_1->get()) continue; if (from_x>range_2->get()) break; float x=from_x-range_1->get(); float y; if (range_1->get()==range_2->get()) y=scale_1->get(); else y=scale_1->get() + x * ( scale_2->get()-scale_1->get() ) / (range_2->get()-range_1->get()); int h=(int)(y*height()); QColor col_from=skin.line_color; col_from.setAlpha(40); QColor col_to=skin.line_color; col_to.setAlpha(200); QLinearGradient gradient(i, height(), i, height()-h); gradient.setColorAt(0,col_from); gradient.setColorAt(1, col_to); p.setBrush(gradient); p.fillRect(i, height()-h,1,h,gradient); } p.drawPixmap(range_1->get()*width()-skin.point_from.width()/2,height()-scale_1->get()*height()-skin.point_from.height()/2,skin.point_from); p.drawPixmap(range_2->get()*width()-skin.point_to.width()/2,height()-scale_2->get()*height()-skin.point_to.height()/2,skin.point_to); /* DRAG TEXT */ if (!click.drag_point) return; char buf[20]; //sprintf is still the best :( bool at_left; bool at_top; if (click.drag_point==1) { sprintf(buf,"%.2f,%.2f",(float)range_1->get(),(float)scale_1->get()); at_left=range_1->get()>0.5; at_top=scale_1->get()<0.5; } else { sprintf(buf,"%.2f,%.2f",(float)range_2->get(),(float)scale_2->get()); at_left=range_2->get()>0.5; at_top=scale_2->get()<0.5; } QString str=buf; QFont font; font.setPixelSize(10); p.setFont(font); QFontMetrics fm(p.font()); int txt_x=at_left?3:width()-(fm.width(str)+3); int txt_y=at_top?(fm.ascent()+3):(height()-(fm.descent()+3)); p.setPen( QColor(0,0,0) ); p.drawText(txt_x-1,txt_y-1,str); p.drawText(txt_x-1,txt_y+1,str); p.drawText(txt_x+1,txt_y-1,str); p.drawText(txt_x+1,txt_y+1,str); p.setPen( QColor(255,255,255) ); p.drawText(txt_x,txt_y,str); }
Expr curl(const Expr& f) { Expr del = gradient(f.size()); return cross(del, f); }
double Adam<DecomposableFunctionType>::Optimize(arma::mat& iterate) { // Find the number of functions to use. const size_t numFunctions = function.NumFunctions(); // This is used only if shuffle is true. arma::Col<size_t> visitationOrder; if (shuffle) visitationOrder = arma::shuffle(arma::linspace<arma::Col<size_t>>(0, (numFunctions - 1), numFunctions)); // To keep track of where we are and how things are going. size_t currentFunction = 0; double overallObjective = 0; double lastObjective = DBL_MAX; // Calculate the first objective function. for (size_t i = 0; i < numFunctions; ++i) overallObjective += function.Evaluate(iterate, i); // Now iterate! arma::mat gradient(iterate.n_rows, iterate.n_cols); //1st moment vector arma::mat mean = arma::zeros<arma::mat>(iterate.n_rows, iterate.n_cols); //2nd moment vector arma::mat variance = arma::zeros<arma::mat>(iterate.n_rows, iterate.n_cols); for (size_t i = 1; i != maxIterations; ++i, ++currentFunction) { // Is this iteration the start of a sequence? if ((currentFunction % numFunctions) == 0) { // Output current objective function. Log::Info << "Adam: iteration " << i << ", objective " << overallObjective << "." << std::endl; if (std::isnan(overallObjective) || std::isinf(overallObjective)) { Log::Warn << "Adam: converged to " << overallObjective << "; terminating with failure. Try a smaller step size?" << std::endl; return overallObjective; } if (std::abs(lastObjective - overallObjective) < tolerance) { Log::Info << "Adam: minimized within tolerance " << tolerance << "; " << "terminating optimization." << std::endl; return overallObjective; } // Reset the counter variables. lastObjective = overallObjective; overallObjective = 0; currentFunction = 0; if (shuffle) // Determine order of visitation. visitationOrder = arma::shuffle(visitationOrder); } // Evaluate the gradient for this iteration. if (shuffle) function.Gradient(iterate, visitationOrder[currentFunction], gradient); else function.Gradient(iterate, currentFunction, gradient); // And update the iterate. // Accumulate updates. mean += (1 - beta1) * (gradient - mean); variance += (1 - beta2) * (gradient % gradient - variance); // Apply update. iterate -= stepSize * mean / (arma::sqrt(variance) + eps); // Now add that to the overall objective function. if (shuffle) overallObjective += function.Evaluate(iterate, visitationOrder[currentFunction]); else overallObjective += function.Evaluate(iterate, currentFunction); } Log::Info << "Adam: maximum iterations (" << maxIterations << ") reached; " << "terminating optimization." << std::endl; // Calculate final objective. overallObjective = 0; for (size_t i = 0; i < numFunctions; ++i) overallObjective += function.Evaluate(iterate, i); return overallObjective; }
////////////////////////////////////////////////////////////////////// // Called to draw an overlay bitmap containing grid and text that // does not need to be recreated every fft data update. ////////////////////////////////////////////////////////////////////// void CPlotter::drawOverlay() { if (m_OverlayPixmap.isNull()) return; int w = m_OverlayPixmap.width(); int h = m_OverlayPixmap.height(); int x,y; float pixperdiv; QRect rect; QPainter painter(&m_OverlayPixmap); painter.initFrom(this); // horizontal grids (size and grid calcs could be moved to resize) m_VerDivs = h/m_VdivDelta+1; m_HorDivs = qMin(w/m_HdivDelta, HORZ_DIVS_MAX); if (m_HorDivs % 2) m_HorDivs++; // we want an odd number of divs so that we have a center line //m_OverlayPixmap.fill(Qt::black); // fill background with gradient QLinearGradient gradient(0, 0, 0 ,h); gradient.setColorAt(0, QColor(0x20,0x20,0x20,0xFF)); gradient.setColorAt(1, QColor(0x4F,0x4F,0x4F,0xFF)); painter.setBrush(gradient); painter.drawRect(0, 0, w, h); // Draw demod filter box if (m_FilterBoxEnabled) { // Clamping no longer necessary as we do it in mouseMove() //ClampDemodParameters(); m_DemodFreqX = xFromFreq(m_DemodCenterFreq); m_DemodLowCutFreqX = xFromFreq(m_DemodCenterFreq + m_DemodLowCutFreq); m_DemodHiCutFreqX = xFromFreq(m_DemodCenterFreq + m_DemodHiCutFreq); int dw = m_DemodHiCutFreqX - m_DemodLowCutFreqX; painter.setBrush(Qt::SolidPattern); painter.setOpacity(0.3); painter.fillRect(m_DemodLowCutFreqX, 0, dw, h, Qt::gray); painter.setOpacity(1.0); painter.setPen(QPen(QColor(0xFF,0x71,0x71,0xFF), 1, Qt::SolidLine)); painter.drawLine(m_DemodFreqX, 0, m_DemodFreqX, h); } // create Font to use for scales QFont Font("Arial"); Font.setPointSize(m_FontSize); QFontMetrics metrics(Font); Font.setWeight(QFont::Normal); painter.setFont(Font); // draw vertical grids pixperdiv = (float)w / (float)m_HorDivs; y = h - h/m_VerDivs/2; painter.setPen(QPen(QColor(0xF0,0xF0,0xF0,0x30), 1, Qt::DotLine)); for (int i = 1; i < m_HorDivs; i++) { x = (int)((float)i*pixperdiv); painter.drawLine(x, 0, x, y); } //Draw Bookmark Tags m_BookmarkTags.clear(); static const QFontMetrics fm(painter.font()); static const int fontHeight = fm.ascent()+1; // height(); static const int slant = 5; static const int levelHeight = fontHeight+5; static const int nLevels = 3; QList<BookmarkInfo> bookmarks = Bookmarks::Get().getBookmarksInRange(m_CenterFreq+m_FftCenter-m_Span/2, m_CenterFreq+m_FftCenter+m_Span/2); int tagEnd[nLevels] = {0}; for(int i=0; i<bookmarks.size(); i++) { x=xFromFreq(bookmarks[i].frequency); #if defined(_WIN16) || defined(_WIN32) || defined(_WIN64) int nameWidth= fm.width(bookmarks[i].name); #else int nameWidth= fm.boundingRect(bookmarks[i].name).width(); #endif int level = 0; for(; level<nLevels && tagEnd[level]>x; level++); level%=nLevels; tagEnd[level]=x+nameWidth+slant-1; m_BookmarkTags.append(qMakePair<QRect, qint64>(QRect(x, level*levelHeight, nameWidth+slant, fontHeight), bookmarks[i].frequency)); QColor color = QColor(bookmarks[i].GetColor()); color.setAlpha(0x60); painter.setPen(QPen(color, 1, Qt::DashLine)); painter.drawLine(x, level*levelHeight+fontHeight+slant, x, y); //Vertical line painter.setPen(QPen(color, 1, Qt::SolidLine)); painter.drawLine(x+slant, level*levelHeight+fontHeight, x+nameWidth+slant-1, level*levelHeight+fontHeight); //Horizontal line painter.drawLine(x+1,level*levelHeight+fontHeight+slant-1, x+slant-1, level*levelHeight+fontHeight+1); //Diagonal line /* painter.setPen(QPen(QColor(0xF0,0xF0,0xF0,0xB0), 1, Qt::SolidLine)); QPolygon polygon(6); polygon.setPoint(0, 0, 10); polygon.setPoint(1, 5, 15); polygon.setPoint(2, 5+nameWidth, 15); polygon.setPoint(3, 5+nameWidth, 0); polygon.setPoint(4, 5, 0); polygon.setPoint(5, 0, 5); polygon.translate(x, level*18); painter.drawPolygon(polygon); */ color.setAlpha(0xFF); painter.setPen(QPen(color, 2, Qt::SolidLine)); painter.drawText(x+slant,level*levelHeight, nameWidth, fontHeight, Qt::AlignVCenter | Qt::AlignHCenter, bookmarks[i].name); } if (m_CenterLineEnabled) { // center line x = xFromFreq(m_CenterFreq); if (x > 0 && x < w) { painter.setPen(QPen(QColor(0x78,0x82,0x96,0xFF), 1, Qt::SolidLine)); painter.drawLine(x, 0, x, y); } } // draw frequency values makeFrequencyStrs(); painter.setPen(QColor(0xD8,0xBA,0xA1,0xFF)); y = h - (h/m_VerDivs); m_XAxisYCenter = h - metrics.height()/2; for (int i = 1; i < m_HorDivs; i++) { x = (int)((float)i*pixperdiv - pixperdiv/2); rect.setRect(x, y, (int)pixperdiv, h/m_VerDivs); painter.drawText(rect, Qt::AlignHCenter|Qt::AlignBottom, m_HDivText[i]); } m_dBStepSize = fabs(m_MaxdB - m_MindB)/(float)m_VerDivs; pixperdiv = (float)h / (float)m_VerDivs; painter.setPen(QPen(QColor(0xF0,0xF0,0xF0,0x30), 1,Qt::DotLine)); for (int i = 1; i < m_VerDivs; i++) { y = (int)((float) i*pixperdiv); painter.drawLine(5*metrics.width("0",-1), y, w, y); } // draw amplitude values painter.setPen(QColor(0xD8,0xBA,0xA1,0xFF)); //Font.setWeight(QFont::Light); painter.setFont(Font); int dB = m_MaxdB; m_YAxisWidth = metrics.width("-120 "); for (int i = 1; i < m_VerDivs; i++) { dB -= m_dBStepSize; // move to end if want to include maxdb y = (int)((float)i*pixperdiv); rect.setRect(0, y-metrics.height()/2, m_YAxisWidth, metrics.height()); painter.drawText(rect, Qt::AlignRight|Qt::AlignVCenter, QString::number(dB)); } if (!m_Running) { // if not running so is no data updates to draw to screen // copy into 2Dbitmap the overlay bitmap. m_2DPixmap = m_OverlayPixmap.copy(0,0,w,h); // trigger a new paintEvent update(); } painter.end(); }
void createCurveIcons() { QDir dir(QDir::current()); if (dir.dirName() == QLatin1String("debug") || dir.dirName() == QLatin1String("release")) { dir.cdUp(); } dir.cdUp(); dir.cdUp(); dir.cdUp(); QSize iconSize(128, 128); QPixmap pix(iconSize); QPainter painter(&pix); QLinearGradient gradient(0,0, 0, iconSize.height()); gradient.setColorAt(0.0, QColor(240, 240, 240)); gradient.setColorAt(1.0, QColor(224, 224, 224)); QBrush brush(gradient); const QMetaObject &mo = QEasingCurve::staticMetaObject; QMetaEnum metaEnum = mo.enumerator(mo.indexOfEnumerator("Type")); QFont oldFont = painter.font(); // Skip QEasingCurve::Custom QString output(QString::fromAscii("%1/images").arg(dir.absolutePath())); printf("Generating images to %s\n", qPrintable(output)); for (int i = 0; i < QEasingCurve::NCurveTypes - 1; ++i) { painter.setFont(oldFont); QString name(QLatin1String(metaEnum.key(i))); painter.fillRect(QRect(QPoint(0, 0), iconSize), brush); QEasingCurve curve((QEasingCurve::Type)i); painter.setPen(QColor(0, 0, 255, 64)); qreal xAxis = iconSize.height()/1.5; qreal yAxis = iconSize.width()/3; painter.drawLine(0, xAxis, iconSize.width(), xAxis); // hor painter.drawLine(yAxis, 0, yAxis, iconSize.height()); // ver qreal curveScale = iconSize.height()/2; painter.drawLine(yAxis - 2, xAxis - curveScale, yAxis + 2, xAxis - curveScale); // hor painter.drawLine(yAxis + curveScale, xAxis + 2, yAxis + curveScale, xAxis - 2); // ver painter.drawText(yAxis + curveScale - 8, xAxis - curveScale - 4, QLatin1String("(1,1)")); painter.drawText(yAxis + 42, xAxis + 10, QLatin1String("progress")); painter.drawText(15, xAxis - curveScale - 10, QLatin1String("value")); painter.setPen(QPen(Qt::red, 1, Qt::DotLine)); painter.drawLine(yAxis, xAxis - curveScale, yAxis + curveScale, xAxis - curveScale); // hor painter.drawLine(yAxis + curveScale, xAxis, yAxis + curveScale, xAxis - curveScale); // ver QPoint start(yAxis, xAxis - curveScale * curve.valueForProgress(0)); painter.setPen(Qt::black); QFont font = oldFont; font.setPixelSize(oldFont.pixelSize() + 15); painter.setFont(font); painter.drawText(0, iconSize.height() - 20, iconSize.width(), 20, Qt::AlignHCenter, name); QPainterPath curvePath; curvePath.moveTo(start); for (qreal t = 0; t <= 1.0; t+=1.0/curveScale) { QPoint to; to.setX(yAxis + curveScale * t); to.setY(xAxis - curveScale * curve.valueForProgress(t)); curvePath.lineTo(to); } painter.setRenderHint(QPainter::Antialiasing, true); painter.strokePath(curvePath, QColor(32, 32, 32)); painter.setRenderHint(QPainter::Antialiasing, false); QString fileName(QString::fromAscii("qeasingcurve-%1.png").arg(name.toLower())); printf("%s\n", qPrintable(fileName)); pix.save(QString::fromAscii("%1/%2").arg(output).arg(fileName), "PNG"); } }
int main(int argc , char* argv[]){ //Program Options po::options_description desc("Allowed Options"); desc.add_options() ("help,h", "Produce this help message") ("startwl,s",po::value<double>(),"Set the start Wavelength for the Analysis") ("stopwl,p",po::value<double>(),"Set the stop Wavelength for the Analysis") ("non-interactive,n","Runs the program in Noninteractive mode. It quits when it's finished") ("version,v","Prints Version") ; po::variables_map vm; po::store(po::parse_command_line(argc,argv,desc),vm); po::notify(vm); if (vm.count("help")) { std::cout << desc<< std::endl; return 3; } if (vm.count("version")) { std::cout << "VCSEL Laser Analysis Version " << _VERSION << std::endl; std::cout << "Using ROOT version " << _ROOT_VERSION << " and Boost version " << _BOOST_VERSION << std::endl; return 0; } if (argc < 4) { std::cout << desc; return 2; } double startwl, stopwl; startwl = 842.; stopwl = 860.; bool run = true; if (vm.count("startwl")) { startwl = vm["startwl"].as<double>(); NUM_ARGS +=2; } if (vm.count("stopwl")) { double tmp = vm["stopwl"].as<double>(); stopwl =tmp; NUM_ARGS +=2; } if (vm.count("non-interactive")) { run = false; NUM_ARGS++; } //checking filetypes must be txt, csv or CSV if (!check_extensions(argc, argv)) { return 1; } std::cout <<"startwl: "<< startwl << '\t' << "stopwl: " << stopwl << std::endl; Double_t max = -210; Double_t maxwl = 0; int _argc = argc; TApplication *t = new TApplication("big",&_argc,argv); std::cout << "Running with boost and ROOT" <<std::endl; std::vector<double> _x,_y; Double_t x[LINES], y[LINES], _inta[LINES], _intb[LINES]; Double_t *cmp_int = new Double_t[argc]; Double_t *argc_ary = new Double_t[argc]; Double_t *cmp_int_root = new Double_t[argc]; Double_t *asymmety_ary = new Double_t[argc]; Double_t *width_ary = new Double_t [argc]; TGraph2D *gr = new TGraph2D(LINES*(argc-1)); //Setting up canvas for plot of all sectrums (is it called spectrums? ;) ) TCanvas *c1 = new TCanvas("All Plots","All Plots",10,10,3000,1500); TH1F *integral_hist = new TH1F("Asymmerty", "Asymmetry", 100,0, 100); if(!(argc % ROWS)){ c1->Divide(argc/ROWS,ROWS); }else{ c1->Divide(argc/ROWS+(argc %ROWS -1),ROWS); } for (Int_t i = NUM_ARGS +1; i < argc ; i++){ try{ max = -211; maxwl = 0; argc_ary[i] = i-NUM_ARGS; std::ifstream in; in.seekg(0, std::ios::beg); // voodoo keep this; char **arg1 = t->Argv() ; std::string tmp = arg1[i]; in.open(tmp.c_str()); std::cout<< "file: " << tmp << std::endl; std::string line; int cline = 0; std::vector<double> a,b, inta, intb; //reading file while(getline(in,line)){ read_file(line, a, b, inta, intb); cline++; } if (cline < LINES){ for(int i = cline ; i < LINES ; i++){ a.push_back(100); b.push_back(-70); } } std::cout<< "\n\ncline: " << cline<< std::endl; cline =(cline > LINES) ? LINES :cline; for(Int_t j = 0; j <LINES ;j++){ x[j] = a[j]; y[j] = b[j]; _inta[j] = inta[j]; _intb[j]= (intb[j] < 0)? 0:intb[j]; } double s_integral = 0; std::cout <<"size of int " << intb.size()<< std::endl; for (size_t it = 0; it < intb.size() - 1; it++){ double y_val = (intb[it]+intb[it+1])/2; assert (y_val >= 0); double area = 0.002*y_val; if(area > 0 ) s_integral += area; } std::cout << "Simpson integral: " <<s_integral <<std::endl; integral_hist->Fill(s_integral); cmp_int[i] = s_integral; Int_t lines = (Int_t)intb.size(); TGraph *r_integral = new TGraph(lines, _inta, _intb); std::cout << "ROOT integral: " << r_integral->Integral() << std::endl; cmp_int_root[i] = r_integral->Integral(); //expanding //expand(y, THRS_EXPAND, RATIO_EXPAND, LINES); //Filling TGraph2D for(Int_t j = 0; j <LINES ; j++){ if (y[j] > max){ max = y[j]; maxwl = x[j]; } gr->SetPoint(j+i*LINES, x[j],i,y[j]); } in.seekg(0, std::ios::beg); in.close(); //Plotting each spectrum TGraph *_gr = new TGraph(LINES,x,y); _gr->GetHistogram()->GetXaxis()->SetTitle("#lambda in nm"); _gr->GetHistogram()->GetYaxis()->SetTitle("Intensity in dB"); c1->cd(i-NUM_ARGS); _gr->Draw("AP"); _gr->GetYaxis()->SetRangeUser(-80.,-10.); _gr->GetXaxis()->SetRangeUser(startwl,stopwl); _gr->SetTitle(tmp.c_str()); c1->Update(); //Calculating asymmetry std::cout << "maximum: " << max << std::endl; double leftlimit, rightlimit = 1; leftlimit = findlower(x,y, max); rightlimit = findupper(x,y, max); if (leftlimit != 1 && rightlimit != 1){ width_ary[i] = (leftlimit +rightlimit)/2; }else{ width_ary[i] = maxwl; } double calced_asy = (maxwl-leftlimit)/(rightlimit-maxwl); asymmety_ary[i-NUM_ARGS] = calced_asy; std::cout << "Asymmetry: " << calced_asy << std::endl; }catch(std::exception e){ std::cout << e.what()<< std::endl; } } //Setting style for 3D Plot TCanvas *d = new TCanvas("big","big",10,10,1500,800); d->Divide(2,2); d->cd(1); TGraph *the_ints = new TGraph(argc-1,argc_ary,cmp_int); the_ints->Draw("A*"); the_ints->SetTitle("My Ints"); d->Update(); d->cd(2); std::cout << "Fitting\n\n"; integral_hist->SetFillColor(kBlue); //settig everything to print fitresuts gStyle->SetOptStat(1211); gStyle->SetOptFit(1111); integral_hist->Draw(); integral_hist->Fit("gaus","W","" ,10,100); //integral_hist->Draw("SAME"); d->Update(); d->cd(3); TGraph *roots_int = new TGraph(argc-1, argc_ary, cmp_int_root); roots_int->SetTitle("ROOTS Int"); roots_int->Draw("A*"); d->Update(); d->cd(4); d->Update(); //gROOT->SetStyle("modern"); gr->SetTitle("big"); gr->GetHistogram("empty")->GetXaxis()->SetTitle("#lambda in nm"); gr->GetHistogram("empty")->GetXaxis()->SetLimits(startwl,stopwl); gr->GetHistogram("empty")->GetYaxis()->SetTitle("Messurement"); gr->GetHistogram("empty")->GetZaxis()->SetTitle("Intensity in dB"); gr->GetHistogram("empty")->GetXaxis()->SetTitleOffset(1.5); gr->GetHistogram("empty")->GetYaxis()->SetTitleOffset(1.5); gr->GetHistogram("empty")->GetZaxis()->SetTitleOffset(1.5); gr->GetHistogram("empty")->GetZaxis()->SetRangeUser(-70.,max); gr->GetHistogram("empty")->GetXaxis()->CenterTitle(); gr->GetHistogram("empty")->GetYaxis()->CenterTitle(); gr->GetHistogram("empty")->GetZaxis()->CenterTitle(); gr->Draw("PCOL"); d->SetFillColor(16); #ifdef RENDER //Render 3D animation const Int_t kUPDATE = 1; TSlider *slider = 0; for (Int_t i = 1; i <= 125; i++){ TView3D *v = new TView3D(); v->RotateView(5+i,45+i,d); //d->Update(); if(i && (i%kUPDATE)== 0){ if (i == kUPDATE){ gr->Draw("PCOL"); d->Update(); slider = new TSlider("slider","test",850,-70,856,max); } if (slider) slider->SetRange(0,Float_t(i)/10000.); d->Modified(); d->Update(); d->Print("3d.gif+"); } } d->Update(); d->Print("3d.gif++"); #endif //Saving image TImage *img = TImage::Create(); boost::filesystem::path p(t->Argv(3)); std::string file = p.parent_path().string(); file += "_big.png"; img->FromPad(d); img->WriteImage(file.c_str()); //cleaning TCanvas *e = new TCanvas("Asymmetry","Asymmetry",10,10,1500,800); e->Divide(2,1); TGraph *asy_plot = new TGraph(argc-1, argc_ary, asymmety_ary); e->cd(1); asy_plot->SetTitle("Asymmetry"); asy_plot->GetHistogram()->GetXaxis()->SetTitle("# Meassurement"); asy_plot->GetHistogram()->GetYaxis()->SetTitle("Asymmetry"); asy_plot->GetHistogram()->GetXaxis()->SetRange(1, argc); asy_plot->Draw("A*"); e->Update(); e->cd(2); TGraph *center_plot = new TGraph(argc-1 , argc_ary, width_ary); center_plot->GetHistogram()->GetXaxis()->SetTitle("# Meassurement"); center_plot->GetHistogram()->GetYaxis()->SetTitle("Center in nm"); center_plot->GetHistogram()->GetYaxis()->SetRangeUser(startwl, stopwl); center_plot->SetTitle("Center"); center_plot->Draw("A*"); e->Update(); //Saving Images TImage *secimg = TImage::Create(); boost::filesystem::path p2(t->Argv(3)); file = p2.parent_path().string(); file += "_asy_cent.png"; secimg->FromPad(e); secimg->WriteImage(file.c_str()); TImage *thrdimg = TImage::Create(); boost::filesystem::path p3(t->Argv(3)); file = p3.parent_path().string(); file += "_allplots.png"; thrdimg->FromPad(c1); thrdimg->WriteImage(file.c_str()); //detecting Gradients gradient(asymmety_ary, width_ary,cmp_int, argc-1,c1); std::cout << "\n\n\nDone !!\nYou can quit now using CTRL+C \n" ; if (run == true){ t->Run(); } std::cout << "With \n" ; delete[] cmp_int; delete[] argc_ary; delete[] cmp_int_root; delete[] asymmety_ary; delete[] width_ary; return 0; }
//---------------------------------------------------------------------------- int ExtractRidges::Main (int, char**) { std::string imageName = Environment::GetPathR("Head.im"); ImageDouble2D image(imageName.c_str()); // Normalize the image values to be in [0,1]. int quantity = image.GetQuantity(); double minValue = image[0], maxValue = minValue; int i; for (i = 1; i < quantity; ++i) { if (image[i] < minValue) { minValue = image[i]; } else if (image[i] > maxValue) { maxValue = image[i]; } } double invRange = 1.0/(maxValue - minValue); for (i = 0; i < quantity; ++i) { image[i] = (image[i] - minValue)*invRange; } // Use first-order centered finite differences to estimate the image // derivatives. The gradient is DF = (df/dx, df/dy) and the Hessian // is D^2F = {{d^2f/dx^2, d^2f/dxdy}, {d^2f/dydx, d^2f/dy^2}}. int xBound = image.GetBound(0); int yBound = image.GetBound(1); int xBoundM1 = xBound - 1; int yBoundM1 = yBound - 1; ImageDouble2D dx(xBound, yBound); ImageDouble2D dy(xBound, yBound); ImageDouble2D dxx(xBound, yBound); ImageDouble2D dxy(xBound, yBound); ImageDouble2D dyy(xBound, yBound); int x, y; for (y = 1; y < yBoundM1; ++y) { for (x = 1; x < xBoundM1; ++x) { dx(x, y) = 0.5*(image(x+1, y) - image(x-1, y)); dy(x, y) = 0.5*(image(x, y+1) - image(x, y-1)); dxx(x, y) = image(x+1, y) - 2.0*image(x, y) + image(x-1, y); dxy(x, y) = 0.25*(image(x+1, y+1) + image(x-1, y-1) - image(x+1, y-1) - image(x-1, y+1)); dyy(x, y) = image(x, y+1) - 2.0*image(x, y) + image(x, y+1); } } dx.Save("dx.im"); dy.Save("dy.im"); dxx.Save("dxx.im"); dxy.Save("dxy.im"); dyy.Save("dyy.im"); // The eigensolver produces eigenvalues a and b and corresponding // eigenvectors U and V: D^2F*U = a*U, D^2F*V = b*V. Define // P = Dot(U,DF) and Q = Dot(V,DF). The classification is as follows. // ridge: P = 0 with a < 0 // valley: Q = 0 with b > 0 ImageDouble2D aImage(xBound, yBound); ImageDouble2D bImage(xBound, yBound); ImageDouble2D pImage(xBound, yBound); ImageDouble2D qImage(xBound, yBound); for (y = 1; y < yBoundM1; ++y) { for (x = 1; x < xBoundM1; ++x) { Vector2d gradient(dx(x, y), dy(x, y)); Matrix2d hessian(dxx(x, y), dxy(x, y), dxy(x, y), dyy(x, y)); EigenDecompositiond decomposer(hessian); decomposer.Solve(true); aImage(x,y) = decomposer.GetEigenvalue(0); bImage(x,y) = decomposer.GetEigenvalue(1); Vector2d u = decomposer.GetEigenvector2(0); Vector2d v = decomposer.GetEigenvector2(1); pImage(x,y) = u.Dot(gradient); qImage(x,y) = v.Dot(gradient); } } aImage.Save("a.im"); bImage.Save("b.im"); pImage.Save("p.im"); qImage.Save("q.im"); // Use a cheap classification of the pixels by testing for sign changes // between neighboring pixels. ImageRGB82D result(xBound, yBound); for (y = 1; y < yBoundM1; ++y) { for (x = 1; x < xBoundM1; ++x) { unsigned char gray = (unsigned char)(255.0f*image(x, y)); double pValue = pImage(x, y); bool isRidge = false; if (pValue*pImage(x-1 ,y) < 0.0 || pValue*pImage(x+1, y) < 0.0 || pValue*pImage(x, y-1) < 0.0 || pValue*pImage(x, y+1) < 0.0) { if (aImage(x, y) < 0.0) { isRidge = true; } } double qValue = qImage(x,y); bool isValley = false; if (qValue*qImage(x-1, y) < 0.0 || qValue*qImage(x+1, y) < 0.0 || qValue*qImage(x, y-1) < 0.0 || qValue*qImage(x, y+1) < 0.0) { if (bImage(x,y) > 0.0) { isValley = true; } } if (isRidge) { if (isValley) { result(x, y) = GetColor24(gray, 0, gray); } else { result(x, y) = GetColor24(gray, 0, 0); } } else if (isValley) { result(x, y) = GetColor24(0, 0, gray); } else { result(x, y) = GetColor24(gray, gray, gray); } } } result.Save("result.im"); return 0; }
void QArcItem::SetPattern(int nPATTERN) { nPatternType = nPATTERN; //样式类型 //QRectF nrect(0,0,qWidth,qHeight); QRectF nrect = this->m_qrcEllipseBndRect; QLinearGradient gradient(nrect.topLeft(),nrect.bottomRight()); QRadialGradient Radial(nrect.center(),nrect.width()/2,nrect.center()); gradient.setSpread(QGradient::PadSpread);// RepeatSpread QBrush br=brush(); br.setColor(nFrontColor); //设置前景色即样式颜色 switch(nPATTERN) { // case 0:br.setStyle(Qt::NoBrush);break; // case 1:br.setColor(nBackColor);br.setStyle(Qt::SolidPattern);break; // case 2:br.setStyle(Qt::Dense1Pattern);break; // case 3:br.setStyle(Qt::Dense2Pattern);break; // case 4:br.setStyle(Qt::Dense3Pattern);break; // case 5:br.setStyle(Qt::Dense4Pattern);break; // case 6:br.setStyle(Qt::Dense5Pattern);break; // case 7:br.setStyle(Qt::Dense6Pattern);break; // case 8:br.setStyle(Qt::Dense7Pattern);break; // case 9:br.setStyle(Qt::HorPattern);break;//setBrush(Qt::HorPattern);break; // case 10:br.setStyle(Qt::VerPattern);break; // case 11:br.setStyle(Qt::CrossPattern);break; // case 12:br.setStyle(Qt::BDiagPattern);break; // case 13:br.setStyle(Qt::FDiagPattern);break; // case 14:br.setStyle(Qt::DiagCrossPattern);break; case 0:br.setStyle(Qt::NoBrush);break;//透明 case 1:br.setColor(nBackColor);br.setStyle(Qt::SolidPattern);break;//纯色 case 2: //横向过度 gradient.setStart(nrect.x(),nrect.y()+nrect.height()); gradient.setColorAt(0,nFrontColor ); gradient.setColorAt(1,nBackColor ); break; case 3: //横向对称过度 gradient.setStart(nrect.x(),nrect.y()+nrect.height()); gradient.setColorAt(0,nFrontColor ); gradient.setColorAt(0.5,nBackColor ); gradient.setColorAt(1,nFrontColor ); break; case 4: //纵向过度 gradient.setStart(nrect.x()+nrect.width(),nrect.y()); gradient.setColorAt(0,nFrontColor ); gradient.setColorAt(1,nBackColor); break; case 5: //纵向对称过度 gradient.setStart(nrect.x()+nrect.width(),nrect.y()); gradient.setColorAt(0,nFrontColor ); gradient.setColorAt(0.5,nBackColor); gradient.setColorAt(1,nFrontColor ); break; case 6: //斜上过度 gradient.setColorAt(0,nFrontColor ); gradient.setColorAt(1,nBackColor ); break; case 7: //斜上对称过度 gradient.setColorAt(0,nFrontColor ); gradient.setColorAt(0.5,nBackColor ); gradient.setColorAt(1,nFrontColor ); break; case 8: //斜下过度 gradient.setStart(nrect.x(),nrect.y()+nrect.height()); gradient.setFinalStop(nrect.x()+nrect.width(),nrect.y()); gradient.setColorAt(0,nBackColor ); gradient.setColorAt(1,nFrontColor); break; case 9: //斜下对称过度 gradient.setStart(nrect.x(),nrect.y()+nrect.height()); gradient.setFinalStop(nrect.x()+nrect.width(),nrect.y()); gradient.setColorAt(0,nFrontColor ); gradient.setColorAt(0.5,nBackColor ); gradient.setColorAt(1,nFrontColor ); break; case 10: //右上角辐射 gradient.setStart(nrect.x()+nrect.width(),nrect.y()); gradient.setFinalStop(nrect.x(),nrect.y()+nrect.height()); gradient.setColorAt(0,nBackColor ); gradient.setColorAt(1,nFrontColor ); break; case 11: //左上角辐射 gradient.setColorAt(0,nBackColor ); gradient.setColorAt(1, nFrontColor); break; case 12: //中心辐射 Radial.setColorAt(0,nBackColor ); Radial.setColorAt(1,nFrontColor ); setBrush(Radial); return; break; case 13: //待操作 Radial.setFocalPoint(nrect.x(),nrect.y()+nrect.height()/2); Radial.setColorAt(0,nBackColor ); Radial.setColorAt(1,nFrontColor ); setBrush(Radial); return; break; default: break; } if(nPATTERN >= 2 ) { setBrush(gradient); } else { setBrush(br); } }
int main(int argc, char *argv[]) { clock_t start_time = clock(); if (argc == 3) { if (sscanf(argv[2], "%lg", &temperature) != 1) { printf("Got bad argument: %s\n", argv[2]); return 1; } temperature *= kB; bool good_element = false; for (int i=0; i<numelements; i++) { if (strcmp(elements[i], argv[1]) == 0) { sigma = sigmas[i]; epsilon = epsilons[i]; good_element = true; } } if (!good_element) { printf("Bad element: %s\n", argv[1]); return 1; } } else { printf("Need element and temperature.\n"); return 1; } char *datname = (char *)malloc(1024); sprintf(datname, "papers/water-saft/figs/hughes-lj-%s-%gK-energy.dat", argv[1], temperature/kB); Functional f = OfEffectivePotential(SaftFluid2(hughes_water_prop.lengthscale, hughes_water_prop.epsilonAB, hughes_water_prop.kappaAB, hughes_water_prop.epsilon_dispersion, hughes_water_prop.lambda_dispersion, hughes_water_prop.length_scaling, 0)); double n_1atm = pressure_to_density(f, temperature, lj_pressure, 0.001, 0.01); double mu = find_chemical_potential(f, temperature, n_1atm); f = OfEffectivePotential(SaftFluid2(hughes_water_prop.lengthscale, hughes_water_prop.epsilonAB, hughes_water_prop.kappaAB, hughes_water_prop.epsilon_dispersion, hughes_water_prop.lambda_dispersion, hughes_water_prop.length_scaling, mu)); Functional S = OfEffectivePotential(EntropySaftFluid2(hughes_water_prop.lengthscale, hughes_water_prop.epsilonAB, hughes_water_prop.kappaAB, hughes_water_prop.epsilon_dispersion, hughes_water_prop.lambda_dispersion, hughes_water_prop.length_scaling)); const double EperVolume = f(temperature, -temperature*log(n_1atm)); const double EperNumber = EperVolume/n_1atm; const double SperNumber = S(temperature, -temperature*log(n_1atm))/n_1atm; const double EperCell = EperVolume*(zmax*ymax*xmax - (4*M_PI/3)*sigma*sigma*sigma); Lattice lat(Cartesian(xmax,0,0), Cartesian(0,ymax,0), Cartesian(0,0,zmax)); GridDescription gd(lat, 0.20); Grid potential(gd); Grid externalpotential(gd); externalpotential.Set(externalpotentialfunction); f = OfEffectivePotential(SaftFluid2(hughes_water_prop.lengthscale, hughes_water_prop.epsilonAB, hughes_water_prop.kappaAB, hughes_water_prop.epsilon_dispersion, hughes_water_prop.lambda_dispersion, hughes_water_prop.length_scaling, mu) + ExternalPotential(externalpotential)); Functional X = WaterX(hughes_water_prop.lengthscale, hughes_water_prop.epsilonAB, hughes_water_prop.kappaAB, hughes_water_prop.epsilon_dispersion, hughes_water_prop.lambda_dispersion, hughes_water_prop.length_scaling, mu); Functional HB = HughesHB(hughes_water_prop.lengthscale, hughes_water_prop.epsilonAB, hughes_water_prop.kappaAB, hughes_water_prop.epsilon_dispersion, hughes_water_prop.lambda_dispersion, hughes_water_prop.length_scaling, mu); externalpotential.epsNativeSlice("papers/water-saft/figs/hughes-lj-potential.eps", Cartesian(0,ymax,0), Cartesian(0,0,zmax), Cartesian(0,ymax/2,zmax/2)); printf("Done outputting hughes-lj-potential.eps\n"); potential = 0*externalpotential - temperature*log(n_1atm)*VectorXd::Ones(gd.NxNyNz); // ??? double energy; { const double surface_tension = 5e-5; // crude guess from memory... const double surfprecision = 1e-4*M_PI*sigma*sigma*surface_tension; // four digits precision const double bulkprecision = 1e-12*fabs(EperCell); // but there's a limit on our precision const double precision = (bulkprecision + surfprecision)*1e-6; Minimizer min = Precision(precision, PreconditionedConjugateGradient(f, gd, temperature, &potential, QuadraticLineMinimizer)); const int numiters = 200; for (int i=0;i<numiters && min.improve_energy(true);i++) { double peak = peak_memory()/1024.0/1024; double current = current_memory()/1024.0/1024; printf("Peak memory use is %g M (current is %g M)\n", peak, current); fflush(stdout); { char* name = new char[1000]; sprintf(name, "papers/water-saft/figs/hughes-lj-%s-%gK-density-%d.eps", argv[1], temperature/kB, i); Grid density(gd, EffectivePotentialToDensity()(temperature, gd, potential)); density.epsNativeSlice(name, Cartesian(0,ymax,0), Cartesian(0,0,zmax), Cartesian(0,ymax/2,zmax/2)); } Grid gradient(gd, potential); gradient *= 0; f.integralgrad(temperature, potential, &gradient); char* gradname = new char[1000]; sprintf(gradname, "papers/water-saft/figs/hughes-lj-%s-%gK-gradient-%d.eps", argv[1], temperature/kB, i); gradient.epsNativeSlice(gradname, Cartesian(0,ymax,0), Cartesian(0,0,zmax), Cartesian(0,ymax/2,zmax/2)); Grid density(gd, EffectivePotentialToDensity()(temperature, gd, potential)); char *plotname = (char *)malloc(1024); sprintf(plotname, "papers/water-saft/figs/hughes-lj-%s-%gK-%d.dat", argv[1], temperature/kB, i); plot_grids_y_direction(plotname, density, gradient); // Grid gradient(gd, potential); // gradient *= 0; // f.integralgrad(temperature, potential, &gradient); // sprintf(name, "papers/water-saft/figs/lj-%s-%d-gradient-big.eps", argv[1], i); // gradient.epsNativeSlice("papers/water-saft/figs/lj-gradient-big.eps", // Cartesian(0,ymax,0), Cartesian(0,0,zmax), // Cartesian(0,ymax/2,zmax/2)); // sprintf(name, "papers/water-saft/figs/lj-%s-%d-big.dat", argv[1], i); // plot_grids_y_direction(name, density, gradient); } double peak = peak_memory()/1024.0/1024; double current = current_memory()/1024.0/1024; printf("Peak memory use is %g M (current is %g M)\n", peak, current); energy = min.energy(); printf("Total energy is %.15g\n", energy); // Here we free the minimizer with its associated data structures. } { double peak = peak_memory()/1024.0/1024; double current = current_memory()/1024.0/1024; printf("Peak memory use is %g M (current is %g M)\n", peak, current); } Grid gradient(gd, potential); gradient *= 0; f.integralgrad(temperature, potential, &gradient); gradient.epsNativeSlice("papers/water-saft/figs/hughes-lj-gradient.eps", Cartesian(0,ymax,0), Cartesian(0,0,zmax), Cartesian(0,ymax/2,zmax/2)); double entropy = S.integral(temperature, potential); Grid density(gd, EffectivePotentialToDensity()(temperature, gd, potential)); // Grid zeroed_out_density(gd, density.cwise()*constraint); // this is zero inside the sphere! Grid X_values(gd, X(temperature, gd, density)); //Grid H_bonds_grid(gd, zeroed_out_density.cwise()*(4*(VectorXd::Ones(gd.NxNyNz)-X_values))); //const double broken_H_bonds = (HB(temperature, n_1atm)/n_1atm)*zeroed_out_density.integrate() - H_bonds_grid.integrate(); //printf("Number of water molecules is %g\n", density.integrate()); printf("The bulk energy per cell should be %g\n", EperCell); printf("The bulk energy based on number should be %g\n", EperNumber*density.integrate()); printf("The bulk entropy is %g/N\n", SperNumber); Functional otherS = EntropySaftFluid2(hughes_water_prop.lengthscale, hughes_water_prop.epsilonAB, hughes_water_prop.kappaAB, hughes_water_prop.epsilon_dispersion, hughes_water_prop.lambda_dispersion, hughes_water_prop.length_scaling); printf("The bulk entropy (haskell) = %g/N\n", otherS(temperature, n_1atm)/n_1atm); //printf("My entropy is %g when I would expect %g\n", entropy, entropy - SperNumber*density.integrate()); double hentropy = otherS.integral(temperature, density); otherS.print_summary(" ", hentropy, "total entropy"); printf("My haskell entropy is %g, when I would expect = %g, difference is %g\n", hentropy, otherS(temperature, n_1atm)*density.integrate()/n_1atm, hentropy - otherS(temperature, n_1atm)*density.integrate()/n_1atm); FILE *o = fopen(datname, "w"); fprintf(o, "%g\t%.15g\t%.15g\t%.15g\n", temperature/kB, energy - EperNumber*density.integrate(), temperature*(entropy - SperNumber*density.integrate()), temperature*(hentropy - otherS(temperature, n_1atm)*density.integrate()/n_1atm)); fclose(o); char *plotname = (char *)malloc(1024); sprintf(plotname, "papers/water-saft/figs/hughes-lj-%s-%gK.dat", argv[1], temperature/kB); //plot_grids_y_direction(plotname, density, X_values); plot_grids_y_direction(plotname, density, gradient); free(plotname); double peak = peak_memory()/1024.0/1024; printf("Peak memory use is %g M\n", peak); double oldN = density.integrate(); density = n_1atm*VectorXd::Ones(gd.NxNyNz);; double hentropyb = otherS.integral(temperature, density); printf("bulklike thingy has %g molecules\n", density.integrate()); otherS.print_summary(" ", hentropyb, "bulk-like entropy"); printf("entropy difference is %g\n", hentropy - hentropyb*oldN/density.integrate()); clock_t end_time = clock(); double seconds = (end_time - start_time)/double(CLOCKS_PER_SEC); double hours = seconds/60/60; printf("Entire calculation took %.0f hours %.0f minutes\n", hours, 60*(hours-floor(hours))); }
void drawDial(const QStyleOptionSlider *option, QPainter *painter) { QPalette pal = option->palette; QColor buttonColor = pal.button().color(); const int width = option->rect.width(); const int height = option->rect.height(); const bool enabled = option->state & QStyle::State_Enabled; qreal r = qMin(width, height) / 2; r -= r/50; const qreal penSize = r/20.0; painter->save(); painter->setRenderHint(QPainter::Antialiasing); // Draw notches if (option->subControls & QStyle::SC_DialTickmarks) { painter->setPen(option->palette.dark().color().darker(120)); painter->drawLines(QStyleHelper::calcLines(option)); } // Cache dial background BEGIN_STYLE_PIXMAPCACHE(QString::fromLatin1("qdial")); p->setRenderHint(QPainter::Antialiasing); const qreal d_ = r / 6; const qreal dx = option->rect.x() + d_ + (width - 2 * r) / 2 + 1; const qreal dy = option->rect.y() + d_ + (height - 2 * r) / 2 + 1; QRectF br = QRectF(dx + 0.5, dy + 0.5, int(r * 2 - 2 * d_ - 2), int(r * 2 - 2 * d_ - 2)); buttonColor.setHsv(buttonColor .hue(), qMin(140, buttonColor .saturation()), qMax(180, buttonColor.value())); QColor shadowColor(0, 0, 0, 20); if (enabled) { // Drop shadow qreal shadowSize = qMax(1.0, penSize/2.0); QRectF shadowRect= br.adjusted(-2*shadowSize, -2*shadowSize, 2*shadowSize, 2*shadowSize); QRadialGradient shadowGradient(shadowRect.center().x(), shadowRect.center().y(), shadowRect.width()/2.0, shadowRect.center().x(), shadowRect.center().y()); shadowGradient.setColorAt(qreal(0.91), QColor(0, 0, 0, 40)); shadowGradient.setColorAt(qreal(1.0), Qt::transparent); p->setBrush(shadowGradient); p->setPen(Qt::NoPen); p->translate(shadowSize, shadowSize); p->drawEllipse(shadowRect); p->translate(-shadowSize, -shadowSize); // Main gradient QRadialGradient gradient(br.center().x() - br.width()/3, dy, br.width()*1.3, br.center().x(), br.center().y() - br.height()/2); gradient.setColorAt(0, buttonColor.lighter(110)); gradient.setColorAt(qreal(0.5), buttonColor); gradient.setColorAt(qreal(0.501), buttonColor.darker(102)); gradient.setColorAt(1, buttonColor.darker(115)); p->setBrush(gradient); } else { p->setBrush(Qt::NoBrush); } p->setPen(QPen(buttonColor.darker(280))); p->drawEllipse(br); p->setBrush(Qt::NoBrush); p->setPen(buttonColor.lighter(110)); p->drawEllipse(br.adjusted(1, 1, -1, -1)); if (option->state & QStyle::State_HasFocus) { QColor highlight = pal.highlight().color(); highlight.setHsv(highlight.hue(), qMin(160, highlight.saturation()), qMax(230, highlight.value())); highlight.setAlpha(127); p->setPen(QPen(highlight, 2.0)); p->setBrush(Qt::NoBrush); p->drawEllipse(br.adjusted(-1, -1, 1, 1)); } END_STYLE_PIXMAPCACHE QPointF dp = calcRadialPos(option, qreal(0.70)); buttonColor = buttonColor.lighter(104); buttonColor.setAlphaF(qreal(0.8)); const qreal ds = r/qreal(7.0); QRectF dialRect(dp.x() - ds, dp.y() - ds, 2*ds, 2*ds); QRadialGradient dialGradient(dialRect.center().x() + dialRect.width()/2, dialRect.center().y() + dialRect.width(), dialRect.width()*2, dialRect.center().x(), dialRect.center().y()); dialGradient.setColorAt(1, buttonColor.darker(140)); dialGradient.setColorAt(qreal(0.4), buttonColor.darker(120)); dialGradient.setColorAt(0, buttonColor.darker(110)); if (penSize > 3.0) { painter->setPen(QPen(QColor(0, 0, 0, 25), penSize)); painter->drawLine(calcRadialPos(option, qreal(0.90)), calcRadialPos(option, qreal(0.96))); } painter->setBrush(dialGradient); painter->setPen(QColor(255, 255, 255, 150)); painter->drawEllipse(dialRect.adjusted(-1, -1, 1, 1)); painter->setPen(QColor(0, 0, 0, 80)); painter->drawEllipse(dialRect); painter->restore(); }
void SheetDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { const QAbstractItemModel *model = index.model(); Q_ASSERT(model); if (!model->parent(index).isValid()) { // this is a top-level item. QStyleOptionButton buttonOption; buttonOption.state = option.state; #ifdef Q_OS_MAC buttonOption.state |= QStyle::State_Raised; #endif buttonOption.state &= ~QStyle::State_HasFocus; buttonOption.rect = option.rect; buttonOption.palette = option.palette; buttonOption.features = QStyleOptionButton::None; painter->save(); QColor buttonColor(230, 230, 230); QBrush buttonBrush = option.palette.button(); if (!buttonBrush.gradient() && buttonBrush.texture().isNull()) buttonColor = buttonBrush.color(); QColor outlineColor = buttonColor.darker(150); QColor highlightColor = buttonColor.lighter(130); // Only draw topline if the previous item is expanded QModelIndex previousIndex = model->index(index.row() - 1, index.column()); bool drawTopline = (index.row() > 0 && m_view->isExpanded(previousIndex)); int highlightOffset = drawTopline ? 1 : 0; QLinearGradient gradient(option.rect.topLeft(), option.rect.bottomLeft()); gradient.setColorAt(0, buttonColor.lighter(102)); gradient.setColorAt(1, buttonColor.darker(106)); painter->setPen(Qt::NoPen); painter->setBrush(gradient); painter->drawRect(option.rect); painter->setPen(highlightColor); painter->drawLine(option.rect.topLeft() + QPoint(0, highlightOffset), option.rect.topRight() + QPoint(0, highlightOffset)); painter->setPen(outlineColor); if (drawTopline) painter->drawLine(option.rect.topLeft(), option.rect.topRight()); painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight()); painter->restore(); QStyleOption branchOption; static const int i = 9; // ### hardcoded in qcommonstyle.cpp QRect r = option.rect; branchOption.rect = QRect(r.left() + i/2, r.top() + (r.height() - i)/2, i, i); branchOption.palette = option.palette; branchOption.state = QStyle::State_Children; if (m_view->isExpanded(index)) branchOption.state |= QStyle::State_Open; m_view->style()->drawPrimitive(QStyle::PE_IndicatorBranch, &branchOption, painter, m_view); // draw text QRect textrect = QRect(r.left() + i*2, r.top(), r.width() - ((5*i)/2), r.height()); QString text = elidedText(option.fontMetrics, textrect.width(), Qt::ElideMiddle, model->data(index, Qt::DisplayRole).toString()); m_view->style()->drawItemText(painter, textrect, Qt::AlignCenter, option.palette, m_view->isEnabled(), text); } else { QItemDelegate::paint(painter, option, index); } }
void EPGItem::paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget*) { QPen pen; QColor gradientColor; // Draw in view's coordinates painter->setWorldMatrixEnabled( false ); // Draw high-quality items //painter->setRenderHint( QPainter::Antialiasing ); // Get the transformations required to map the text on the viewport QTransform viewPortTransform = m_view->viewportTransform(); QRectF mapped = deviceTransform( viewPortTransform ).mapRect( boundingRect() ); QLinearGradient gradient( mapped.topLeft(), mapped.bottomLeft() ); bool b_simultaneous = playsAt( m_view->baseTime() ); if ( m_current || b_simultaneous ) gradientColor.setRgb( 244, 125, 0 , b_simultaneous ? 192 : 255 ); else gradientColor.setRgb( 201, 217, 242 ); gradient.setColorAt( 0.0, gradientColor.lighter( 120 ) ); gradient.setColorAt( 1.0, gradientColor ); pen.setColor( option->state & QStyle::State_MouseOver || hasFocus() ? QColor( 0, 0, 0 ) : QColor( 192, 192, 192 ) ); pen.setStyle( option->state & QStyle::State_MouseOver && !hasFocus() ? Qt::DashLine : Qt::SolidLine ); painter->setBrush( QBrush( gradient ) ); painter->setPen( pen ); mapped.adjust( 1, 2, -1, -2 ); painter->drawRoundedRect( mapped, 10, 10 ); /* Draw text */ // Setup the font QFont f = painter->font(); // Get the font metrics QFontMetrics fm = painter->fontMetrics(); // Adjust the drawing rect mapped.adjust( 6, 6, -6, -6 ); painter->setPen( Qt::black ); /* Draw the title. */ painter->drawText( mapped, Qt::AlignTop | Qt::AlignLeft, fm.elidedText( m_name, Qt::ElideRight, mapped.width() ) ); mapped.adjust( 0, 20, 0, 0 ); QDateTime m_end = m_start.addSecs( m_duration ); f.setPixelSize( 10 ); f.setItalic( true ); painter->setFont( f ); /* Draw the hours. */ painter->drawText( mapped, Qt::AlignTop | Qt::AlignLeft, fm.elidedText( start().toString( "hh:mm" ) + " - " + m_end.toString( "hh:mm" ), Qt::ElideRight, mapped.width() ) ); }
void GradientDialog::accept() { emit applyGradient( gradient() ); QDialog::accept(); }
int main(int argc, char **argv) { int spi_fd; int effect=EFFECT_RANDOM; if (argc>1) { if ((!strncmp(argv[1],"-h",2)) || (!strncmp(argv[1],"help",4))) { help(argv[0]); return 0; } if (!strncmp(argv[1],"bargraph_mannual",15)) { effect=EFFECT_BARGRAPH_MANUAL; } if (!strncmp(argv[1],"bargraph",8)) { effect=EFFECT_BARGRAPH; } if (!strncmp(argv[1],"disable",7)) { effect=EFFECT_DISABLE; } if (!strncmp(argv[1],"falling",7)) { effect=EFFECT_FALLING; } if (!strncmp(argv[1],"fish",4)) { effect=EFFECT_FISH; } if (!strncmp(argv[1],"gradient",8)) { effect=EFFECT_GRADIENT; } if (!strncmp(argv[1],"noise",5)) { effect=EFFECT_NOISE; } if (!strncmp(argv[1],"pulsar",6)) { effect=EFFECT_PULSAR; } if (!strncmp(argv[1],"rainbow",7)) { effect=EFFECT_RAINBOW; } if (!strncmp(argv[1],"stars",5)) { effect=EFFECT_STARS; } if (!strncmp(argv[1],"red_green",9)) { effect=EFFECT_RED_GREEN; } if (!strncmp(argv[1],"blue_yellow",11)) { effect=EFFECT_BLUE_YELLOW; } if (!strncmp(argv[1],"two_color_scroll",15)) { effect=EFFECT_TWO_COLOR_SCROLL; } if (!strncmp(argv[1],"scanner_blinky",14)) { effect=EFFECT_SCANNER_BLINKY; } else if (!strncmp(argv[1],"scanner_dual",12)) { effect=EFFECT_SCANNER_DUAL; } else if (!strncmp(argv[1],"scanner_random",14)) { effect=EFFECT_SCANNER_RANDOM; } else if (!strncmp(argv[1],"scanner",7)) { effect=EFFECT_SCANNER; } } spi_fd=lpd8806_init(); if (spi_fd<0) { exit(-1); } switch(effect) { case EFFECT_BARGRAPH: bargraph(spi_fd,argc>2?argv[2]:NULL, argc>3?argv[3]:NULL); break; case EFFECT_BARGRAPH_MANUAL: bargraph_manual(spi_fd,argc>2?argv[2]:NULL, argc>3?argv[3]:NULL); break; case EFFECT_DISABLE: disable(spi_fd); break; case EFFECT_FALLING: falling(spi_fd, argc>2?argv[2]:NULL, argc>2?argv[3]:NULL); break; case EFFECT_FISH: fish(spi_fd,argc>2?argv[2]:NULL); break; case EFFECT_GRADIENT: gradient(spi_fd,argc>2?argv[2]:NULL); break; case EFFECT_NOISE: noise(spi_fd); break; case EFFECT_PULSAR: pulsar(spi_fd,argc>2?argv[2]:NULL); break; case EFFECT_RAINBOW: rainbow(spi_fd); break; case EFFECT_STARS: stars(spi_fd,argc>2?argv[2]:NULL, argc>3?argv[3]:NULL); break; case EFFECT_TWO_COLOR_SCROLL: two_color_scroll(spi_fd, argc>2?argv[2]:NULL, argc>3?argv[3]:NULL, argc>4?argv[4]:NULL); break; case EFFECT_RED_GREEN: two_color_scroll(spi_fd, "red", "green", "1"); break; case EFFECT_BLUE_YELLOW: two_color_scroll(spi_fd, "blue", "yellow", "0"); break; case EFFECT_SCANNER: scanner(spi_fd,argc>2?argv[2]:NULL); break; case EFFECT_SCANNER_BLINKY: scanner_blinky(spi_fd); break; case EFFECT_SCANNER_DUAL: scanner_dual(spi_fd, argc>2?argv[2]:NULL, argc>3?argv[3]:NULL); break; case EFFECT_SCANNER_RANDOM: scanner_random(spi_fd); break; } lpd8806_close(spi_fd); return 0; }
void Light::paint(QPainter *p, const QRectF& boundingRect, const QPointF& mousePos, bool mouseIn, const bool isRotated) { if (!mouseIn && state()!=QAbstractAnimation::Running) return; QRectF drawRect(boundingRect); // XXX: ugly hack because I don't know the real contents area of the FrameSvg //drawRect.adjust(-3, -3, +3, +3); qreal width = drawRect.width(); qreal height = drawRect.height(); qreal size = 0.5; qreal x; qreal y; QColor lightColor(m_item->icon()->highlightColor()); //qDebug() << "W:" << width << "H:" << height << "X:" << drawRect.left() << "Y:" << drawRect.top(); //qDebug() << "light paint "<< m_currentAnimation << ' ' << m_progress; switch (m_currentAnimation) { case StartupAnimation: case AttentionAnimation: x = drawRect.left() + width * 0.5; y = drawRect.top() + height * 0.5; size = size * 2.0 * (m_progress < 0.5 ? (m_progress * 0.5 + 0.5) : (1 - m_progress / 2)); break; case NoAnimation: if (isRotated) { x = m_item->size().height() - mousePos.y(); y = mousePos.x(); } else { x = mousePos.x(); y = mousePos.y(); } // y = drawRect.top() + height * 1.10; width *= 2.0; height *= 2.0; break; default: return; } QRadialGradient gradient(0.5, 0.5, size); gradient.setCoordinateMode(QRadialGradient::ObjectBoundingMode); lightColor.setAlpha(200); gradient.setColorAt(0.0, lightColor); lightColor.setAlpha(60); gradient.setColorAt(0.6, lightColor); lightColor.setAlpha(0); gradient.setColorAt(1.0, lightColor); p->setClipRect(drawRect); p->fillRect( x - width * 0.5, y - height * 0.5, width, height, gradient); p->setClipping(false); }
void GridItemDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { PlayableItem* item = m_model->sourceModel()->itemFromIndex( m_model->mapToSource( index ) ); if ( !item || !index.isValid() ) return; QStyleOptionViewItemV4 opt = option; initStyleOption( &opt, QModelIndex() ); qApp->style()->drawControl( QStyle::CE_ItemViewItem, &opt, painter ); QRect r = option.rect; QString top, bottom; if ( !item->album().isNull() ) { top = item->album()->name(); if ( !item->album()->artist().isNull() ) bottom = item->album()->artist()->name(); } else if ( !item->artist().isNull() ) { top = item->artist()->name(); } else if ( !item->query().isNull() ) { top = item->query()->track(); bottom = item->query()->artist(); } else { return; } painter->save(); painter->setRenderHint( QPainter::Antialiasing ); if ( !m_covers.contains( index ) ) { if ( !item->album().isNull() ) { m_covers.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->album(), r.size(), TomahawkUtils::Grid ) ) ); } else if ( !item->artist().isNull() ) { m_covers.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->artist(), r.size(), TomahawkUtils::Grid ) ) ); } else { m_covers.insert( index, QSharedPointer< Tomahawk::PixmapDelegateFader >( new Tomahawk::PixmapDelegateFader( item->query(), r.size(), TomahawkUtils::Grid ) ) ); } NewClosure( m_covers[ index ], SIGNAL( repaintRequest() ), const_cast<GridItemDelegate*>(this), SLOT( doUpdateIndex( QPersistentModelIndex ) ), QPersistentModelIndex( index ) )->setAutoDelete( false ); } QSharedPointer< Tomahawk::PixmapDelegateFader > fader = m_covers[ index ]; if ( fader->size() != r.size() ) fader->setSize( r.size() ); const QPixmap cover = fader->currentPixmap(); painter->drawPixmap( r, cover ); qreal opacity = -1.; if ( m_hoverFaders.contains( index ) ) { const qreal pct = ( m_hoverFaders[ index ]->currentFrame() / 100.0 ); opacity = 0.35 - pct * 0.35; } else if ( m_hoverIndex == index ) { opacity = 0.35; } if ( opacity > -1.0 ) { painter->save(); painter->setPen( QColor( "dddddd" ) ); painter->setBrush( QColor( "#dddddd" ) ); painter->setOpacity( opacity ); painter->drawRect( r ); painter->restore(); } QTextOption to; to.setWrapMode( QTextOption::NoWrap ); QString text; QFont font = opt.font; font.setPointSize( TomahawkUtils::defaultFontSize() ); QFont boldFont = font; boldFont.setBold( true ); boldFont.setPointSize( TomahawkUtils::defaultFontSize() + 1 ); int bottomHeight = QFontMetrics( font ).boundingRect( bottom ).height(); int topHeight = QFontMetrics( boldFont ).boundingRect( top ).height(); int frameHeight = bottomHeight + topHeight + 10; QColor c1; c1.setRgb( 0, 0, 0 ); c1.setAlphaF( 0.00 ); QColor c2; c2.setRgb( 0, 0, 0 ); c2.setAlphaF( 0.88 ); QRect gradientRect = r.adjusted( 0, r.height() - frameHeight * 2, 0, 0 ); QLinearGradient gradient( QPointF( 0, 0 ), QPointF( 0, 1 ) ); gradient.setCoordinateMode( QGradient::ObjectBoundingMode ); gradient.setColorAt( 0.0, c1 ); gradient.setColorAt( 0.6, c2 ); gradient.setColorAt( 1.0, c2 ); painter->save(); painter->setPen( Qt::transparent ); painter->setBrush( gradient ); painter->drawRect( gradientRect ); painter->restore(); painter->setPen( TomahawkUtils::Colors::SELECTION_FOREGROUND ); QRect textRect = option.rect.adjusted( 6, option.rect.height() - frameHeight, -6, -6 ); bool oneLiner = false; if ( bottom.isEmpty() ) oneLiner = true; painter->setFont( boldFont ); if ( oneLiner ) { to.setAlignment( Qt::AlignHCenter | Qt::AlignVCenter ); text = painter->fontMetrics().elidedText( top, Qt::ElideRight, textRect.width() - 3 ); painter->drawText( textRect, text, to ); } else { to.setAlignment( Qt::AlignHCenter | Qt::AlignTop ); text = painter->fontMetrics().elidedText( top, Qt::ElideRight, textRect.width() - 3 ); painter->drawText( textRect, text, to ); painter->setFont( font ); // If the user is hovering over an artist rect, draw a background so she knows it's clickable QRect r = textRect; r.setTop( r.bottom() - painter->fontMetrics().height() ); r.adjust( 4, 0, -4, -1 ); if ( m_hoveringOver == index ) { TomahawkUtils::drawQueryBackground( painter, r ); painter->setPen( TomahawkUtils::Colors::SELECTION_FOREGROUND ); } to.setAlignment( Qt::AlignHCenter | Qt::AlignBottom ); text = painter->fontMetrics().elidedText( bottom, Qt::ElideRight, textRect.width() - 10 ); painter->drawText( textRect.adjusted( 5, -1, -5, -1 ), text, to ); // Calculate rect of artist on-hover button click area m_artistNameRects[ index ] = r; } painter->restore(); }
void MapperGradSimilar::calculate( const cv::Mat& img1, const cv::Mat& image2, cv::Ptr<Map>& res) const { Mat gradx, grady, imgDiff; Mat img2; CV_DbgAssert(img1.size() == image2.size()); CV_DbgAssert(img1.channels() == image2.channels()); CV_DbgAssert(img1.channels() == 1 || img1.channels() == 3); if(!res.empty()) { // We have initial values for the registration: we move img2 to that initial reference res->inverseWarp(image2, img2); } else { img2 = image2; } // Get gradient in all channels gradient(img1, img2, gradx, grady, imgDiff); // Matrices with reference frame coordinates Mat grid_r, grid_c; grid(img1, grid_r, grid_c); // Calculate parameters using least squares Matx<double, 4, 4> A; Vec<double, 4> b; // For each value in A, all the matrix elements are added and then the channels are also added, // so we have two calls to "sum". The result can be found in the first element of the final // Scalar object. Mat xIx_p_yIy = grid_c.mul(gradx); xIx_p_yIy += grid_r.mul(grady); Mat yIx_m_xIy = grid_r.mul(gradx); yIx_m_xIy -= grid_c.mul(grady); A(0, 0) = sum(sum(sqr(xIx_p_yIy)))[0]; A(0, 1) = sum(sum(xIx_p_yIy.mul(yIx_m_xIy)))[0]; A(0, 2) = sum(sum(gradx.mul(xIx_p_yIy)))[0]; A(0, 3) = sum(sum(grady.mul(xIx_p_yIy)))[0]; A(1, 1) = sum(sum(sqr(yIx_m_xIy)))[0]; A(1, 2) = sum(sum(gradx.mul(yIx_m_xIy)))[0]; A(1, 3) = sum(sum(grady.mul(yIx_m_xIy)))[0]; A(2, 2) = sum(sum(sqr(gradx)))[0]; A(2, 3) = sum(sum(gradx.mul(grady)))[0]; A(3, 3) = sum(sum(sqr(grady)))[0]; // Lower half values (A is symmetric) A(1, 0) = A(0, 1); A(2, 0) = A(0, 2); A(3, 0) = A(0, 3); A(2, 1) = A(1, 2); A(3, 1) = A(1, 3); A(3, 2) = A(2, 3); // Calculation of b b(0) = -sum(sum(imgDiff.mul(xIx_p_yIy)))[0]; b(1) = -sum(sum(imgDiff.mul(yIx_m_xIy)))[0]; b(2) = -sum(sum(imgDiff.mul(gradx)))[0]; b(3) = -sum(sum(imgDiff.mul(grady)))[0]; // Calculate affine transformation. We use Cholesky decomposition, as A is symmetric. Vec<double, 4> k = A.inv(DECOMP_CHOLESKY)*b; Matx<double, 2, 2> linTr(k(0) + 1., k(1), -k(1), k(0) + 1.); Vec<double, 2> shift(k(2), k(3)); if(res.empty()) { res = Ptr<Map>(new MapAffine(linTr, shift)); } else { MapAffine newTr(linTr, shift); res->compose(newTr); } }
SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle *networkStyle) : QWidget(0, f), curAlignment(0) { // set reference point, paddings int paddingRight = 50; int paddingTop = 50; int titleVersionVSpace = 17; int titleCopyrightVSpace = 40; float fontFactor = 1.0; float devicePixelRatio = 1.0; #if QT_VERSION > 0x050100 devicePixelRatio = ((QGuiApplication*)QCoreApplication::instance())->devicePixelRatio(); #endif // define text to place QString titleText = tr("Moselbit Core"); QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers")); QString titleAddText = networkStyle->getTitleAddText(); QString font = QApplication::font().toString(); // create a bitmap according to device pixelratio QSize splashSize(480*devicePixelRatio,320*devicePixelRatio); pixmap = QPixmap(splashSize); #if QT_VERSION > 0x050100 // change to HiDPI if it makes sense pixmap.setDevicePixelRatio(devicePixelRatio); #endif QPainter pixPaint(&pixmap); pixPaint.setPen(QColor(100,100,100)); // draw a slightly radial gradient QRadialGradient gradient(QPoint(0,0), splashSize.width()/devicePixelRatio); gradient.setColorAt(0, Qt::white); gradient.setColorAt(1, QColor(247,247,247)); QRect rGradient(QPoint(0,0), splashSize); pixPaint.fillRect(rGradient, gradient); // draw the moselbit icon, expected size of PNG: 1024x1024 QRect rectIcon(QPoint(-150,-122), QSize(430,430)); const QSize requiredSize(1024,1024); QPixmap icon(networkStyle->getAppIcon().pixmap(requiredSize)); pixPaint.drawPixmap(rectIcon, icon); // check font size and drawing with pixPaint.setFont(QFont(font, 33*fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if(titleTextWidth > 160) { // strange font rendering, Arial probably not found fontFactor = 0.75; } pixPaint.setFont(QFont(font, 33*fontFactor)); fm = pixPaint.fontMetrics(); titleTextWidth = fm.width(titleText); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight,paddingTop,titleText); pixPaint.setFont(QFont(font, 15*fontFactor)); // if the version string is to long, reduce size fm = pixPaint.fontMetrics(); int versionTextWidth = fm.width(versionText); if(versionTextWidth > titleTextWidth+paddingRight-10) { pixPaint.setFont(QFont(font, 10*fontFactor)); titleVersionVSpace -= 5; } pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 10*fontFactor)); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText); // draw additional text if special network if(!titleAddText.isEmpty()) { QFont boldFont = QFont(font, 10*fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int titleAddTextWidth = fm.width(titleAddText); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleAddTextWidth-10,15,titleAddText); } pixPaint.end(); // Set window title setWindowTitle(titleText + " " + titleAddText); // Resize window and move to center of desktop, disallow resizing QRect r(QPoint(), QSize(pixmap.size().width()/devicePixelRatio,pixmap.size().height()/devicePixelRatio)); resize(r.size()); setFixedSize(r.size()); move(QApplication::desktop()->screenGeometry().center() - r.center()); subscribeToCoreSignals(); }
void KCategoryDrawer::drawCategory(const QModelIndex &index, int /*sortRole*/, const QStyleOption &option, QPainter *painter) const { painter->setRenderHint(QPainter::Antialiasing); const QString category = index.model()->data(index, KCategorizedSortFilterProxyModel::CategoryDisplayRole).toString(); const QRect optRect = option.rect; QFont font(QApplication::font()); font.setBold(true); const QFontMetrics fontMetrics = QFontMetrics(font); QColor outlineColor = option.palette.text().color(); outlineColor.setAlphaF(0.35); //BEGIN: top left corner { painter->save(); painter->setPen(outlineColor); const QPointF topLeft(optRect.topLeft()); QRectF arc(topLeft, QSizeF(4, 4)); arc.translate(0.5, 0.5); painter->drawArc(arc, 1440, 1440); painter->restore(); } //END: top left corner //BEGIN: left vertical line { QPoint start(optRect.topLeft()); start.ry() += 3; QPoint verticalGradBottom(optRect.topLeft()); verticalGradBottom.ry() += fontMetrics.height() + 5; QLinearGradient gradient(start, verticalGradBottom); gradient.setColorAt(0, outlineColor); gradient.setColorAt(1, Qt::transparent); painter->fillRect(QRect(start, QSize(1, fontMetrics.height() + 5)), gradient); } //END: left vertical line //BEGIN: horizontal line { QPoint start(optRect.topLeft()); start.rx() += 3; QPoint horizontalGradTop(optRect.topLeft()); horizontalGradTop.rx() += optRect.width() - 6; painter->fillRect(QRect(start, QSize(optRect.width() - 6, 1)), outlineColor); } //END: horizontal line //BEGIN: top right corner { painter->save(); painter->setPen(outlineColor); QPointF topRight(optRect.topRight()); topRight.rx() -= 4; QRectF arc(topRight, QSizeF(4, 4)); arc.translate(0.5, 0.5); painter->drawArc(arc, 0, 1440); painter->restore(); } //END: top right corner //BEGIN: right vertical line { QPoint start(optRect.topRight()); start.ry() += 3; QPoint verticalGradBottom(optRect.topRight()); verticalGradBottom.ry() += fontMetrics.height() + 5; QLinearGradient gradient(start, verticalGradBottom); gradient.setColorAt(0, outlineColor); gradient.setColorAt(1, Qt::transparent); painter->fillRect(QRect(start, QSize(1, fontMetrics.height() + 5)), gradient); } //END: right vertical line //BEGIN: text { QRect textRect(option.rect); textRect.setTop(textRect.top() + 7); textRect.setLeft(textRect.left() + 7); textRect.setHeight(fontMetrics.height()); textRect.setRight(textRect.right() - 7); painter->save(); painter->setFont(font); QColor penColor(option.palette.text().color()); penColor.setAlphaF(0.6); painter->setPen(penColor); painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, category); painter->restore(); } //END: text }
//----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- void tTideGraph::paintEvent( QPaintEvent* pEvent ) { tTideCurrentGraphBase::paintEvent( pEvent ); int w = contentsRect().width(); int h = contentsRect().height(); QPainter p( this ); p.setRenderHint( QPainter::Antialiasing, true ); p.setClipRect( contentsRect() ); QRect r( QPoint(0,0), contentsRect().size() ); // lets translate the painter so we can work with a 0,0 origin p.save(); p.translate( contentsRect().topLeft() ); //###### 1) Paint background and the daylight area if(m_SunRiseX <= m_SunSetX) { // left night p.fillRect( 0, 0, m_SunRiseX, h, palette().dark() ); // day p.fillRect( m_SunRiseX, 0, m_SunSetX - m_SunRiseX, h, palette().light() ); // right night p.fillRect( m_SunSetX, 0, w - m_SunSetX, h, palette().dark() ); } else if(m_SunRiseX > m_SunSetX) { // left day p.fillRect( 0, 0, m_SunSetX, h, palette().light() ); // night p.fillRect( m_SunSetX, 0, m_SunRiseX - m_SunSetX, h, palette().dark() ); // right day p.fillRect( m_SunRiseX, 0, w - m_SunRiseX, h, palette().light() ); } //###### 2) Add legend backgrounds QColor c = palette().text().color(); c.setAlpha( 127 ); p.fillRect( 0, h - BOTTOM_MARGIN_HEIGHT, w, BOTTOM_MARGIN_HEIGHT, QBrush( c ) ); p.fillRect( 0, 0, LEFT_MARGIN_WIDTH, h, palette().base() ); // we have finished doing work with a 0,0 origin p.restore(); //###### 3) Left depth legend and grid lines p.rotate(-90); p.setRenderHint( QPainter::Antialiasing, false ); c.setAlpha( 63 ); QPen pen( QBrush( c ), 0 ); qreal rangeDiv = GetRangeDivision( tConvert::Instance()->ToUser(UNITS_DEPTH, m_HeightUnits, static_cast<float>(m_GraphConfig.m_DeltaY)) ); float stepSize = tConvert::Instance()->UserToBase( UNITS_DEPTH, static_cast<float>(rangeDiv) ); stepSize = tConvert::Instance()->BaseToSpecifiedUnits(UNITS_DEPTH, m_HeightUnits, stepSize); for( qreal pxY = 0, strY = 0; pxY <= m_GraphConfig.m_MaxY; pxY += stepSize, strY += rangeDiv ) { p.setPen( palette().text().color() ); p.drawText(RotatedTextELeftMargin(0, pxY, 40), Qt::AlignCenter, QString("%1").arg(strY) ); p.setPen( pen ); p.drawLine(RotatedGraphToPixel(0, pxY), RotatedGraphToPixel(1, pxY)); } for( qreal pxY = 0, strY = 0; pxY >= m_GraphConfig.m_MinY; pxY -= stepSize, strY += rangeDiv ) { p.setPen( palette().text().color() ); p.drawText(RotatedTextELeftMargin(0, pxY, 40), Qt::AlignCenter, QString("%1").arg(strY) ); p.setPen( pen ); p.drawLine(RotatedGraphToPixel(0, pxY), RotatedGraphToPixel(1, pxY)); } p.rotate(90); p.drawLine( QPointF( GraphToPixel(0.25, 0).x(), 0 ), QPointF( GraphToPixel(0.25, 0).x(), h ) ); p.drawLine( QPointF( GraphToPixel(0.5, 0).x(), 0 ), QPointF( GraphToPixel(0.5, 0).x(), h ) ); p.drawLine( QPointF( GraphToPixel(0.75, 0).x(), 0 ), QPointF( GraphToPixel(0.75, 0).x(), h ) ); p.setRenderHint( QPainter::Antialiasing, true ); //###### 4) Graph and fill the tides spline QPainterPath path; path.moveTo( GraphToPixel(0, 0) ); for( int i = 0; i < m_TideHeights.size(); ++i ) { // source data is in 10 minute intervals => 1/144 of a day path.lineTo( GraphToPixel( m_TideHeights.at(i).x(), m_TideHeights.at(i).y() ) ); } // Close the path path.lineTo( GraphToPixel(1, 0) ); path.lineTo( GraphToPixel(0, 0) ); //###### 5) Fill graph path QLinearGradient gradient(0,0,0,h); QColor endColor = palette().highlight().color(); endColor.setAlpha( 191 ); QColor midColor = palette().highlight().color().lighter( 130 ); midColor.setAlpha( 191 ); gradient.setColorAt(0.0, endColor); gradient.setColorAt(0.1, endColor); gradient.setColorAt(0.5, midColor); gradient.setColorAt(0.9, endColor); gradient.setColorAt(1.0, endColor); p.fillPath(path, gradient); p.save(); QPen penGraph( palette().base().color() ); penGraph.setWidth(2); p.setPen(penGraph); p.drawPath(path); p.restore(); //###### 6) Draw over with text p.setPen( palette().base().color() ); qSort(m_TideExtremes); for( int i = 0; i < m_TideExtremes.size(); ++i ) { // Convert time into decimal qreal timePos = GetTimeF( m_TideExtremes.at(i).first ); // Draw on height (and compensate for user units) float convertedHeight = tConvert::Instance()->ToUser(UNITS_DEPTH, m_HeightUnits, static_cast<float>(m_TideExtremes.at(i).second) ); QString unitsString = tConvert::Instance()->GetUnitsString( UNITS_DEPTH ); QString heightString = QString("%1 ").arg(convertedHeight, 2, 'f', qAbs(convertedHeight) > 1 ? 1 : 2) + unitsString; QString timeString = m_TideExtremes.at(i).first.toString( tSystemSettings::Instance()->TimeFormatString() ); QRect boundRectHeight = TextBoundingRect( timePos, 0, fontMetrics().width( heightString ), eBottomMarginHeight ); QRect boundRectTime = TextBoundingRect( timePos, 0, fontMetrics().width( timeString ), eBottomMarginTime ); QPen curPen = p.pen(); if( i < m_TideExtremes.size() - 1 ) { if( m_TideExtremes[i].second < m_TideExtremes[i+1].second ) { p.setPen(Qt::red); } } else { if( m_TideExtremes[i].second < m_TideExtremes[i-1].second ) { p.setPen(Qt::red); } } p.drawText( boundRectHeight, Qt::AlignCenter, heightString ); p.drawText( boundRectTime, Qt::AlignCenter, timeString ); p.setPen(curPen); // Draw on time // Draw triangle } //####### 7) Draw on the sun times //(SUN) p.setPen( palette().text().color() ); if(m_SunRiseTime.isValid()) { QString riseString = tr("Sunrise") + " " + m_SunRiseTime.toString( tSystemSettings::Instance()->TimeFormatString() ); QRect boundSunRise = TextBoundingRect( GetTimeF( m_SunRiseTime ), m_GraphConfig.m_MinY, fontMetrics().width( riseString ), eSunTime); p.drawText(boundSunRise, Qt::AlignCenter, riseString ); } if(m_SunSetTime.isValid()) { QString sunsetString = tr("Sunset") + " " + m_SunSetTime.toString( tSystemSettings::Instance()->TimeFormatString() ); QRect boundSunSet = TextBoundingRect( GetTimeF( m_SunSetTime ), m_GraphConfig.m_MinY, fontMetrics().width( sunsetString ), eSunTime); p.drawText(boundSunSet, Qt::AlignCenter, sunsetString ); } //####### 8) Draw the time and height for the present time tDateTime currentDateTime = tDateTime::currentDateTime(); //QDateTime does not know time zone / local time offset. if( m_UseUTCTime ) { currentDateTime = currentDateTime.toUTC(); } if(m_ActiveDate.date() == currentDateTime.date()) { qreal currentTime = GetTimeF( currentDateTime.time() ); qreal height = GetHeightAtTime( currentTime ); float convertedHeight = tConvert::Instance()->ToUser(UNITS_DEPTH, m_HeightUnits, static_cast<float>(height) ); QString unitsString = tConvert::Instance()->GetUnitsString( UNITS_DEPTH ); QString heightString = QString("%1 ").arg(convertedHeight, 2, 'f', qAbs(convertedHeight) > 1 ? 1 : 2) + unitsString; QString timeString = currentDateTime.time().toString( tSystemSettings::Instance()->TimeFormatString() ); QRect boundCurrentHeight = TextBoundingRect( currentTime, 0, fontMetrics().width( heightString ), eCurrentHeight ); QRect boundCurrentTime = TextBoundingRect( currentTime, 0, fontMetrics().width( timeString ), eCurrentTime ); p.setPen( palette().text().color() ); p.drawText( boundCurrentHeight, Qt::AlignCenter, heightString ); p.drawText( boundCurrentTime, Qt::AlignCenter, timeString ); QPen penRed(Qt::red); p.setPen(penRed); p.setRenderHint( QPainter::Antialiasing, false ); p.drawLine( GraphToPixel(currentTime, m_GraphConfig.m_MinY).toPoint(), GraphToPixel(currentTime, m_GraphConfig.m_MaxY).toPoint() - QPoint(0,1) ); } }
tmp<Field<Type> > fixedGradientCorrectedFvPatchField<Type>:: gradientBoundaryCoeffs() const { return gradient(); }
int lua_texture::_set_gradient_alpha(lua_State* pLua) { if (!check_parent_()) return 0; lua::function mFunc("Texture:set_gradient_alpha", pLua); mFunc.add(0, "orientation", lua::TYPE_STRING); mFunc.add(1, "min red", lua::TYPE_NUMBER); mFunc.add(2, "min green", lua::TYPE_NUMBER); mFunc.add(3, "min blue", lua::TYPE_NUMBER); mFunc.add(4, "min alpha", lua::TYPE_NUMBER); mFunc.add(5, "max red", lua::TYPE_NUMBER); mFunc.add(6, "max green", lua::TYPE_NUMBER); mFunc.add(7, "max blue", lua::TYPE_NUMBER); mFunc.add(8, "max alpha", lua::TYPE_NUMBER); mFunc.new_param_set(); mFunc.add(0, "min color", lua::TYPE_STRING); mFunc.add(1, "max color", lua::TYPE_STRING); if (mFunc.check()) { std::string sOrientation = mFunc.get(0)->get_string(); gradient::orientation mOrientation; if (sOrientation == "HORIZONTAL") mOrientation = gradient::HORIZONTAL; else if (sOrientation == "VERTICAL") mOrientation = gradient::VERTICAL; else { gui::out << gui::warning << mFunc.get_name() << " : " "Unknown gradient orientation : \""+sOrientation+"\"." << std::endl; return mFunc.on_return(); } if (mFunc.get_param_set_rank() == 0) { pTextureParent_->set_gradient(gradient( mOrientation, color( mFunc.get(1)->get_number(), mFunc.get(2)->get_number(), mFunc.get(3)->get_number(), mFunc.get(4)->get_number() ), color( mFunc.get(5)->get_number(), mFunc.get(6)->get_number(), mFunc.get(7)->get_number(), mFunc.get(8)->get_number() ) )); } else { pTextureParent_->set_gradient(gradient( mOrientation, color(mFunc.get(0)->get_string()), color(mFunc.get(1)->get_string()) )); } } return mFunc.on_return(); }
QPixmap FoundCountIcon::circledTextPixmap(const QString &text, int height, const QFont &font, const QColor &color) const { QString key = QString("BLI-%1.%2.%3.%4") .arg(text).arg(height).arg(font.toString()).arg(color.rgb()); if (QPixmap* cached = QPixmapCache::find(key)) { return *cached; } // Compute the sizes of the image components: QRectF textRect = QFontMetrics(font).boundingRect(0, 0, /*width=*/1, height, Qt::AlignLeft | Qt::AlignTop, text); qreal xMargin = height / 6; qreal width = xMargin + textRect.width() + xMargin; // Create the gradient image: QPixmap gradient(3 * width, 3 * height); // We double the size to be able to smooth scale down it (== antialiased curves) QPainter gradientPainter(&gradient); #if 1 // Enable the new look of the gradient: const QPalette& palette = m_basketTree->palette(); QColor topColor = palette.color(QPalette::Highlight).lighter(130); //120 QColor topMidColor = palette.color(QPalette::Highlight).lighter(105); //105 QColor bottomMidColor = palette.color(QPalette::Highlight).darker(130); //120 QColor bottomColor = palette.color(QPalette::Highlight); drawGradient(&gradientPainter, topColor, topMidColor, 0, 0, gradient.width(), gradient.height() / 2, /*sunken=*/false, /*horz=*/true, /*flat=*/false); drawGradient(&gradientPainter, bottomMidColor, bottomColor, 0, gradient.height() / 2, gradient.width(), gradient.height() - gradient.height() / 2, /*sunken=*/false, /*horz=*/true, /*flat=*/false); gradientPainter.fillRect(0, 0, gradient.width(), 3, palette.color(QPalette::Highlight)); #else drawGradient(&gradientPainter, palette().color(QPalette::Highlight), palette().color(QPalette::Highlight).darker(), 0, 0, gradient.width(), gradient.height(), /*sunken=*/false, /*horz=*/true, /*flat=*/false); #endif gradientPainter.end(); // Draw the curved rectangle: QBitmap curvedRectangle(3 * width, 3 * height); curvedRectangle.fill(Qt::color0); QPainter curvePainter(&curvedRectangle); curvePainter.setPen(Qt::color1); curvePainter.setBrush(Qt::color1); curvePainter.setClipRect(0, 0, 3*(height / 5), 3*(height)); // If the width is small, don't fill the right part of the pixmap curvePainter.drawEllipse(0, 3*(-height / 4), 3*(height), 3*(height * 3 / 2)); // Don't forget we double the sizes curvePainter.setClipRect(3*(width - height / 5), 0, 3*(height / 5), 3*(height)); curvePainter.drawEllipse(3*(width - height), 3*(-height / 4), 3*(height), 3*(height * 3 / 2)); curvePainter.setClipping(false); curvePainter.fillRect(3*(height / 6), 0, 3*(width - 2 * height / 6), 3*(height), curvePainter.brush()); curvePainter.end(); // Apply the curved rectangle as the mask of the gradient: gradient.setMask(curvedRectangle); QImage resultImage = gradient.toImage(); //resultImage.setAlphaBuffer(true); resultImage.convertToFormat(QImage::Format_ARGB32); // Scale down the image smoothly to get anti-aliasing: QPixmap pmScaled = QPixmap::fromImage(resultImage.scaled(width, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); // Draw the text, and return the result: QPainter painter(&pmScaled); painter.setPen(color); painter.setFont(font); painter.drawText(0 + 1, 0, width, height, Qt::AlignHCenter | Qt::AlignVCenter, text); painter.end(); QPixmapCache::insert(key, pmScaled); return pmScaled; }
SplashScreen::SplashScreen(interfaces::Node& node, Qt::WindowFlags f, const NetworkStyle *networkStyle) : QWidget(0, f), curAlignment(0), m_node(node) { // set reference point, paddings int paddingRight = 50; int paddingTop = 50; int titleVersionVSpace = 17; int titleCopyrightVSpace = 40; float fontFactor = 1.0; float devicePixelRatio = 1.0; #if QT_VERSION > 0x050100 devicePixelRatio = static_cast<QGuiApplication*>(QCoreApplication::instance())->devicePixelRatio(); #endif // define text to place QString titleText = tr(PACKAGE_NAME); QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText = QString::fromUtf8(CopyrightHolders(strprintf("\xc2\xA9 %u-%u ", 2013, COPYRIGHT_YEAR)).c_str()); QString titleAddText = networkStyle->getTitleAddText(); QString font = QApplication::font().toString(); // create a bitmap according to device pixelratio QSize splashSize(480*devicePixelRatio,320*devicePixelRatio); pixmap = QPixmap(splashSize); #if QT_VERSION > 0x050100 // change to HiDPI if it makes sense pixmap.setDevicePixelRatio(devicePixelRatio); #endif QPainter pixPaint(&pixmap); pixPaint.setPen(QColor(100,100,100)); // draw a slightly radial gradient QRadialGradient gradient(QPoint(0,0), splashSize.width()/devicePixelRatio); gradient.setColorAt(0, Qt::white); gradient.setColorAt(1, QColor(247,247,247)); QRect rGradient(QPoint(0,0), splashSize); pixPaint.fillRect(rGradient, gradient); // draw the bitcoin icon, expected size of PNG: 1024x1024 QRect rectIcon(QPoint(-150,-122), QSize(430,430)); const QSize requiredSize(1024,1024); QPixmap icon(networkStyle->getAppIcon().pixmap(requiredSize)); pixPaint.drawPixmap(rectIcon, icon); // check font size and drawing with pixPaint.setFont(QFont(font, 33*fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if (titleTextWidth > 176) { fontFactor = fontFactor * 176 / titleTextWidth; } pixPaint.setFont(QFont(font, 33*fontFactor)); fm = pixPaint.fontMetrics(); titleTextWidth = fm.width(titleText); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight,paddingTop,titleText); pixPaint.setFont(QFont(font, 15*fontFactor)); // if the version string is too long, reduce size fm = pixPaint.fontMetrics(); int versionTextWidth = fm.width(versionText); if(versionTextWidth > titleTextWidth+paddingRight-10) { pixPaint.setFont(QFont(font, 10*fontFactor)); titleVersionVSpace -= 5; } pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText); // draw copyright stuff { pixPaint.setFont(QFont(font, 10*fontFactor)); const int x = pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight; const int y = paddingTop+titleCopyrightVSpace; QRect copyrightRect(x, y, pixmap.width() - x - paddingRight, pixmap.height() - y); pixPaint.drawText(copyrightRect, Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, copyrightText); } // draw additional text if special network if(!titleAddText.isEmpty()) { QFont boldFont = QFont(font, 10*fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int titleAddTextWidth = fm.width(titleAddText); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleAddTextWidth-10,15,titleAddText); } pixPaint.end(); // Set window title setWindowTitle(titleText + " " + titleAddText); // Resize window and move to center of desktop, disallow resizing QRect r(QPoint(), QSize(pixmap.size().width()/devicePixelRatio,pixmap.size().height()/devicePixelRatio)); resize(r.size()); setFixedSize(r.size()); move(QApplication::desktop()->screenGeometry().center() - r.center()); subscribeToCoreSignals(); installEventFilter(this); }
void KateCategoryDrawer::drawCategory(const QModelIndex &index, int sortRole, const QStyleOption &option, QPainter *painter) const { Q_UNUSED( sortRole ) painter->setRenderHint(QPainter::Antialiasing); const QRect optRect = option.rect; QFont font(QApplication::font()); font.setBold(true); const QFontMetrics fontMetrics = QFontMetrics(font); const int height = categoryHeight(index, option); const bool leftToRight = painter->layoutDirection() == Qt::LeftToRight; //BEGIN: decoration gradient { QPainterPath path(optRect.bottomLeft()); path.lineTo(QPoint(optRect.topLeft().x(), optRect.topLeft().y() - 3)); const QPointF topLeft(optRect.topLeft()); QRectF arc(topLeft, QSizeF(4, 4)); path.arcTo(arc, 180, -90); path.lineTo(optRect.topRight()); path.lineTo(optRect.bottomRight()); path.lineTo(optRect.bottomLeft()); QColor window(option.palette.window().color()); const QColor base(option.palette.base().color()); window.setAlphaF(0.4); QLinearGradient decoGradient1; if (leftToRight) { decoGradient1.setStart(optRect.topLeft()); decoGradient1.setFinalStop(optRect.bottomLeft()); } else { decoGradient1.setStart(optRect.topRight()); decoGradient1.setFinalStop(optRect.bottomRight()); } decoGradient1.setColorAt(0, window); decoGradient1.setColorAt(1, Qt::transparent); QLinearGradient decoGradient2; if (leftToRight) { decoGradient2.setStart(optRect.topLeft()); decoGradient2.setFinalStop(optRect.topRight()); } else { decoGradient2.setStart(optRect.topRight()); decoGradient2.setFinalStop(optRect.topLeft()); } decoGradient2.setColorAt(0, Qt::transparent); decoGradient2.setColorAt(1, base); painter->fillPath(path, decoGradient1); painter->fillPath(path, decoGradient2); } //END: decoration gradient { QRect newOptRect(optRect); if (leftToRight) { newOptRect.translate(1, 1); } else { newOptRect.translate(-1, 1); } //BEGIN: inner top left corner { painter->save(); painter->setPen(option.palette.base().color()); QRectF arc; if (leftToRight) { const QPointF topLeft(newOptRect.topLeft()); arc = QRectF(topLeft, QSizeF(4, 4)); arc.translate(0.5, 0.5); painter->drawArc(arc, 1440, 1440); } else { QPointF topRight(newOptRect.topRight()); topRight.rx() -= 4; arc = QRectF(topRight, QSizeF(4, 4)); arc.translate(-0.5, 0.5); painter->drawArc(arc, 0, 1440); } painter->restore(); } //END: inner top left corner //BEGIN: inner left vertical line { QPoint start; QPoint verticalGradBottom; if (leftToRight) { start = newOptRect.topLeft(); verticalGradBottom = newOptRect.topLeft(); } else { start = newOptRect.topRight(); verticalGradBottom = newOptRect.topRight(); } start.ry() += 3; verticalGradBottom.ry() += newOptRect.height() - 3; QLinearGradient gradient(start, verticalGradBottom); gradient.setColorAt(0, option.palette.base().color()); gradient.setColorAt(1, Qt::transparent); painter->fillRect(QRect(start, QSize(1, newOptRect.height() - 3)), gradient); } //END: inner left vertical line //BEGIN: inner horizontal line { QPoint start; QPoint horizontalGradTop; if (leftToRight) { start = newOptRect.topLeft(); horizontalGradTop = newOptRect.topLeft(); start.rx() += 3; horizontalGradTop.rx() += newOptRect.width() - 3; } else { start = newOptRect.topRight(); horizontalGradTop = newOptRect.topRight(); start.rx() -= 3; horizontalGradTop.rx() -= newOptRect.width() - 3; } QLinearGradient gradient(start, horizontalGradTop); gradient.setColorAt(0, option.palette.base().color()); gradient.setColorAt(1, Qt::transparent); QSize rectSize; if (leftToRight) { rectSize = QSize(newOptRect.width() - 3, 1); } else { rectSize = QSize(-newOptRect.width() + 3, 1); } painter->fillRect(QRect(start, rectSize), gradient); } //END: inner horizontal line } QColor outlineColor = option.palette.text().color(); outlineColor.setAlphaF(0.35); //BEGIN: top left corner { painter->save(); painter->setPen(outlineColor); QRectF arc; if (leftToRight) { const QPointF topLeft(optRect.topLeft()); arc = QRectF(topLeft, QSizeF(4, 4)); arc.translate(0.5, 0.5); painter->drawArc(arc, 1440, 1440); } else { QPointF topRight(optRect.topRight()); topRight.rx() -= 4; arc = QRectF(topRight, QSizeF(4, 4)); arc.translate(-0.5, 0.5); painter->drawArc(arc, 0, 1440); } painter->restore(); } //END: top left corner //BEGIN: left vertical line { QPoint start; QPoint verticalGradBottom; if (leftToRight) { start = optRect.topLeft(); verticalGradBottom = optRect.topLeft(); } else { start = optRect.topRight(); verticalGradBottom = optRect.topRight(); } start.ry() += 3; verticalGradBottom.ry() += optRect.height() - 3; QLinearGradient gradient(start, verticalGradBottom); gradient.setColorAt(0, outlineColor); gradient.setColorAt(1, option.palette.base().color()); painter->fillRect(QRect(start, QSize(1, optRect.height() - 3)), gradient); } //END: left vertical line //BEGIN: horizontal line { QPoint start; QPoint horizontalGradTop; if (leftToRight) { start = optRect.topLeft(); horizontalGradTop = optRect.topLeft(); start.rx() += 3; horizontalGradTop.rx() += optRect.width() - 3; } else { start = optRect.topRight(); horizontalGradTop = optRect.topRight(); start.rx() -= 3; horizontalGradTop.rx() -= optRect.width() - 3; } QLinearGradient gradient(start, horizontalGradTop); gradient.setColorAt(0, outlineColor); gradient.setColorAt(1, option.palette.base().color()); QSize rectSize; if (leftToRight) { rectSize = QSize(optRect.width() - 3, 1); } else { rectSize = QSize(-optRect.width() + 3, 1); } painter->fillRect(QRect(start, rectSize), gradient); } //END: horizontal line //BEGIN: draw text { const QString category = index.model()->data(index, Qt::DisplayRole).toString(); // KCategorizedSortFilterProxyModel::CategoryDisplayRole).toString(); QRect textRect = QRect(option.rect.topLeft(), QSize(option.rect.width() - 2 - 3 - 3, height)); textRect.setTop(textRect.top() + 2 + 3 /* corner */); textRect.setLeft(textRect.left() + 2 + 3 /* corner */ + 3 /* a bit of margin */); painter->save(); painter->setFont(font); QColor penColor(option.palette.text().color()); penColor.setAlphaF(0.6); painter->setPen(penColor); painter->drawText(textRect, Qt::AlignLeft | Qt::AlignTop, category); painter->restore(); } //END: draw text }