void IntervalProgressDisplay::drawBeatCircles(QPainter& p, int hRadius, int vRadius, int beatCircles, int offset) {
    paintEllipticalPath(p, hRadius, vRadius);

    double angle = -PI / 2.0;

    const float FIRST_COLOR_POSITION = 0.0f;
    const float SECOND_COLOR_POSITION = 0.99f;

    //float hRadius = width()/2;
    //float vRadius = height()/2;

    for (int i = 0; i < beatCircles; i++) {

        int x = centerX + (hRadius  * std::cos(angle));// - ovalSize /2;
        int y = (centerY + (vRadius * std::sin(angle))) + ovalSize/2;

        QRadialGradient brush(x + ovalSize/2, y, ovalSize*2);
        QPen pen(Qt::NoPen);

        //p->drawLine(0, centerY, width(), centerY);

        //beat not played yet
        brush.setColorAt(FIRST_COLOR_POSITION, Qt::gray);
        brush.setColorAt(SECOND_COLOR_POSITION, Qt::black);

        bool isIntervalFirstBeat = i + offset == 0;
        bool isMeasureFirstBeat = (i + offset) % beatsPerAccent == 0;
        if (i + offset == currentBeat && (isIntervalFirstBeat || isMeasureFirstBeat)) {//first beats
            if( isIntervalFirstBeat || isShowingAccents() ){
                brush.setColorAt(FIRST_COLOR_POSITION, QColor(255, 100, 100));//accent beat colors
                brush.setColorAt(SECOND_COLOR_POSITION, Qt::red);
            }
            else{
                brush.setColorAt(FIRST_COLOR_POSITION, Qt::green); //playing beat highlight colors
                brush.setColorAt(SECOND_COLOR_POSITION, Qt::darkGreen);
            }
            pen.setColor(Qt::darkGray);
            pen.setStyle(Qt::SolidLine);
        }
        else{
            if((i + offset) % beatsPerAccent == 0 && (i+offset) > currentBeat){
                if(isShowingAccents()){
                    brush.setColorAt(FIRST_COLOR_POSITION, Qt::white); //accent marks
                    brush.setColorAt(SECOND_COLOR_POSITION, Qt::gray);

                    pen.setColor(Qt::gray);
                    pen.setStyle(Qt::SolidLine);
                }
            }
            else if ( (i + offset) <= currentBeat) {
                if(i + offset < currentBeat){
                    brush.setColorAt(FIRST_COLOR_POSITION, PLAYED_BEATS_FIRST_COLOR); //played beats
                    brush.setColorAt(SECOND_COLOR_POSITION, PLAYED_BEATS_SECOND_COLOR);
                }
                else{//the current beat is highlighted
                    brush.setColorAt(FIRST_COLOR_POSITION, Qt::green); //playing beat highlight colors
                    brush.setColorAt(SECOND_COLOR_POSITION, Qt::darkGreen);

                    pen.setColor(Qt::darkGreen);
                    pen.setStyle(Qt::SolidLine);
                }
            }
        }

        p.setBrush(brush);
        p.setPen( pen );
        int size = (i + offset) == currentBeat ? ovalSize + 1 : ovalSize;
        p.drawEllipse( QPoint(x, y), size, size);

        if(offset > 0 && currentBeat < offset){//is drawing the first circles?
            p.setBrush(QColor(255,255, 255, 200)); //the internal circles are drawed transparent
            p.drawEllipse( QPoint(x, y), size, size);
        }

        angle -= 2 * -PI / beatCircles;

    }
}
void FilmstripFrameHeadGadget::drawOnionSkinSelection(QPainter &p, const QColor &lightColor, const QColor &darkColor)
{
	int currentRow = getCurrentFrame();

	TPixel frontPixel, backPixel;
	bool inksOnly;
	Preferences::instance()->getOnionData(frontPixel, backPixel, inksOnly);
	QColor frontColor((int)frontPixel.r, (int)frontPixel.g, (int)frontPixel.b, 128);
	QColor backColor((int)backPixel.r, (int)backPixel.g, (int)backPixel.b, 128);

	OnionSkinMask osMask = TApp::instance()->getCurrentOnionSkin()->getOnionSkinMask();
	int mosCount = osMask.getMosCount();

	int i;
	//OnionSkinの円の左上座標のy値
	int onionDotYPos = m_dy / 2 - 5;

	p.setPen(Qt::red);
	//--- OnionSkinが有効なら実線、無効なら点線
	if (!osMask.isEnabled()) {
		QPen currentPen = p.pen();
		currentPen.setStyle(Qt::DashLine);
		currentPen.setColor(QColor(128, 128, 128, 255));
		p.setPen(currentPen);
	}
	//カレントフレームにOnionSkinを伸ばすハンドルを描画
	{
		int angle180 = 16 * 180;
		QRectF handleRect(0, 0, 30, 30);

		//上向きのハンドル:1フレーム目のときは描画しない
		if (currentRow > 0) {
			int y0 = index2y(currentRow) - 15;
			p.setBrush(QBrush(backColor));
			p.drawChord(handleRect.translated(0, y0), 0, angle180);
		}

		//下向きのハンドル:最終フレームの時は描画しない
		std::vector<TFrameId> fids;
		m_filmstrip->getLevel()->getFids(fids);
		int frameCount = (int)fids.size();
		if (currentRow < frameCount - 1) {
			int y1 = index2y(currentRow + 1) - 15;
			p.setBrush(QBrush(frontColor));
			p.drawChord(handleRect.translated(0, y1), angle180, angle180);
		}

		//--- 動く Onion Skinの描画 その1
		//先に線を描く
		//まず OnionSkinの最大/最小値を取得
		int minMos = 0;
		int maxMos = 0;
		for (i = 0; i < mosCount; i++) {
			int mos = osMask.getMos(i);
			if (minMos > mos)
				minMos = mos;
			if (maxMos < mos)
				maxMos = mos;
		}
		p.setBrush(Qt::NoBrush);
		//min/maxが更新されていたら、線を描く
		if (minMos < 0) //上方向に伸ばす線
		{
			int y0 = index2y(currentRow + minMos) + onionDotYPos + 10; //10は●の直径
			int y1 = index2y(currentRow) - 15;
			p.drawLine(15, y0, 15, y1);
		}
		if (maxMos > 0) //下方向に伸ばす線
		{
			int y0 = index2y(currentRow + 1) + 15;
			int y1 = index2y(currentRow + maxMos) + onionDotYPos;
			p.drawLine(15, y0, 15, y1);
		}
	}

	//--- Fix Onion Skinの描画
	for (i = 0; i < osMask.getFosCount(); i++) {
		int fos = osMask.getFos(i);
		//if(fos == currentRow) continue;
		int y = index2y(fos) + onionDotYPos;
		p.setPen(Qt::red);
		//OnionSkinがDisableなら中空にする
		p.setBrush(osMask.isEnabled() ? QBrush(QColor(0, 255, 255, 128)) : Qt::NoBrush);
		p.drawEllipse(0, y, 10, 10);
	}
	//---

	//--- 動く Onion Skinの描画 その2

	//続いて、各OnionSkinの●を描く
	p.setPen(Qt::red);
	for (i = 0; i < mosCount; i++) {
		//mosはOnionSkinの描かれるフレームのオフセット値
		int mos = osMask.getMos(i);
		//100312 iwasawa ハイライトする場合は後で描くのでスキップする
		if (currentRow + mos == m_highlightedMosFrame)
			continue;

		int y = index2y(currentRow + mos) + onionDotYPos;

		p.setBrush(mos < 0 ? backColor : frontColor);

		p.drawEllipse(10, y, 10, 10);
	}

	//Fix Onion Skin ハイライトの描画 FixOnionSkinがマウスが乗ってハイライトされていて、
	//かつ 現在のフレームでないときに描画
	if (m_highlightedFosFrame >= 0 && m_highlightedFosFrame != currentRow) {
		p.setPen(QColor(255, 128, 0));
		p.setBrush(QBrush(QColor(255, 255, 0, 200)));
		p.drawEllipse(0, index2y(m_highlightedFosFrame) + onionDotYPos, 10, 10);
	}

	//通常のOnion Skin ハイライトの描画
	if (m_highlightedMosFrame >= 0 && m_highlightedMosFrame != currentRow) {
		p.setPen(QColor(255, 128, 0));
		p.setBrush(QBrush(QColor(255, 255, 0, 200)));
		p.drawEllipse(10, index2y(m_highlightedMosFrame) + onionDotYPos, 10, 10);
	}
}
Example #3
0
void QtGrid::drawDiagonals( QPainter &painter )
{
    painter.setPen( QPen( diagonal_color, 1 ) );
    //painter.drawLine( ( int )x(), ( int )y(), ( int )x() + _width, ( int )y() + _height );
    //painter.drawLine( ( int )x(), ( int )y() + _height, ( int )x() + _width, ( int )y() );
}
void GraphScale::Draw(QPainter &painter)
{
    double scale;
    int x,y,w,w_max,font_h = QFontMetrics(font).height();

    painter.setPen(pen);
    painter.setFont(font);

    switch (pos)
    {
      case pos_bottom:
        scale = graph->w / (vmax-vmin);
        painter.drawLine(graph->xo,graph->yo,graph->xo+graph->w,graph->yo);
        for (double v=vmin;v<=vmax;v+=vinc)
        {
            QString s = (labdps<0 ? QString("%1").arg(v/labdiv) : QString("%1").arg(v/labdiv, 0, 'f', labdps)) + labsuffix;

            x=graph->xo + (v-vmin)*scale;
        //printf("x=%d\n",x);
            painter.drawLine(x,graph->yo,x,graph->yo + 10);
            x=x - QFontMetrics(font).boundingRect(s).width()/2;
            painter.drawText(x,graph->yo + 10 + font_h,s);
        }
        break;

    case pos_left:
        scale = graph->h / (vmax-vmin);
        painter.drawLine(graph->xo,graph->yo,graph->xo,graph->yo-graph->h);
        w_max=0;
        for (double v=vmin;v<=vmax;v+=vinc)
        {
            QString s = (labdps<0 ? QString("%1").arg(v/labdiv) : QString("%1").arg(v/labdiv, 0, 'f', labdps)) + labsuffix;
            y=graph->yo - (v-vmin)*scale;
            painter.drawLine(graph->xo,y,graph->xo-10,y);
            w = QFontMetrics(font).boundingRect(s).width();
            x=graph->xo - 12 - w;
            painter.drawText(x,y + font_h/2.5,s);
            if (w>w_max) w_max=w;
        }
        if (!title.isEmpty())
        {
            x=graph->xo;
            y=graph->yo - graph->h/2.0;
            w=QFontMetrics(font).boundingRect(title).width();
            painter.save();
            painter.translate(x,y);
            painter.rotate(-90.0);
            painter.drawText(-w/2.0,-w_max-font_h-4,title);
            painter.restore();
        }
        break;

    case pos_right:
        scale = graph->h / (vmax-vmin);
        painter.drawLine(graph->xo+graph->w,graph->yo,graph->xo+graph->w,graph->yo-graph->h);
        w_max=0;
        for (double v=vmin;v<=vmax;v+=vinc)
        {
//printf("scalev=%lf\n",v);
            QString s = (labdps<0 ? QString("%1").arg(v/labdiv) : QString("%1").arg(v/labdiv, 0, 'f', labdps)) + labsuffix;
            x=graph->xo + graph->w;
            y=graph->yo - (v-vmin)*scale;
            w = QFontMetrics(font).boundingRect(s).width();
            painter.drawLine(x,y,x+10,y);
            painter.drawText(x+12,y + font_h/2.5,s);
            if (w>w_max) w_max=w;
        }
        if (!title.isEmpty())
        {
            x=graph->xo + graph->w;
            y=graph->yo - graph->h/2.0;
            w=QFontMetrics(font).boundingRect(title).width();
            painter.save();
            painter.translate(x,y);
            painter.rotate(90.0);
            painter.drawText(-w/2.0,-w_max-font_h-4,title);
            painter.restore();
        }
        break;

      default: break;
    }
}
Example #5
0
void ContinuousPanel::draw(QPainter& painter, const QList<Element*>& el) {
      painter.save();
      painter.setRenderHint(QPainter::Antialiasing, preferences.antialiasedDrawing);
      painter.setRenderHint(QPainter::TextAntialiasing, true);

      // Draw colored rectangle
      painter.setClipping(false);
      QPointF pos(_offsetPanel, 0);
      painter.translate(pos);
      QPen pen;
      pen.setWidthF(0.0);
      pen.setStyle(Qt::NoPen);
      painter.setPen(pen);
      painter.setBrush(preferences.fgColor);
      QRectF bg(_rect);
      bg.setWidth(_widthClef + _widthKeySig + _widthTimeSig + _leftMarginTotal + _panelRightPadding);
      QPixmap* fgPixmap = _sv->fgPixmap();
      if (fgPixmap == 0 || fgPixmap->isNull())
            painter.fillRect(bg, preferences.fgColor);
      else {
            painter.setMatrixEnabled(false);
            painter.drawTiledPixmap(bg, *fgPixmap, bg.topLeft()
               - QPoint(lrint(_sv->matrix().dx()), lrint(_sv->matrix().dy())));
            painter.setMatrixEnabled(true);
            }

      painter.setClipRect(_rect);
      painter.setClipping(true);

      QColor color(MScore::layoutBreakColor);

      // Draw measure text number
      QString text = _mmRestCount ? QString("#%1-%2").arg(_currentMeasureNo+1).arg(_currentMeasureNo+_mmRestCount) : QString("#%1").arg(_currentMeasureNo+1);
      Text* newElement = new Text(_score);
      newElement->setTextStyleType(TextStyleType::DEFAULT);
      newElement->setFlag(ElementFlag::MOVABLE, false);
      newElement->setXmlText(text);
      newElement->textStyle().setFamily("FreeSans");
      newElement->textStyle().setSizeIsSpatiumDependent(true);
      newElement->setColor(color);
      newElement->sameLayout();
      pos = QPointF(_score->styleP(StyleIdx::clefLeftMargin) + _widthClef, _y + newElement->height());
      painter.translate(pos);
      newElement->draw(&painter);
      pos += QPointF(_offsetPanel, 0);
      painter.translate(-pos);
      delete newElement;

      // This second pass draws the elements spaced evently using the width of the largest element
      for (const Element* e : el) {
            e->itemDiscovered = 0;
            if (!e->visible()) {
                  if (_score->printing() || !_score->showInvisible())
                        continue;
                  }

           if (e->type() == Element::Type::STAFF_LINES) {
                  Staff* currentStaff = _score->staff(e->staffIdx());
                  Segment* parent = _score->tick2segmentMM(_currentMeasureTick);

                  pos = QPointF (_offsetPanel, e->pagePos().y());
                  painter.translate(pos);

                  // Draw staff lines
                  StaffLines* newStaffLines = static_cast<StaffLines*>(e->clone());
                  newStaffLines->setWidth(bg.width());
                  newStaffLines->setParent(parent);
                  newStaffLines->setTrack(e->track());
                  newStaffLines->layout();
                  newStaffLines->setColor(color);
                  newStaffLines->draw(&painter);
                  delete newStaffLines;

                  // Draw barline
                  BarLine* newBarLine = new BarLine(_score);
                  newBarLine->setBarLineType(BarLineType::NORMAL);
                  newBarLine->setParent(parent);
                  newBarLine->setTrack(e->track());
                  newBarLine->setSpan(currentStaff->barLineSpan());
                  newBarLine->setSpanFrom(currentStaff->barLineFrom());
                  newBarLine->setSpanTo(currentStaff->barLineTo());
                  newBarLine->layout();
                  newBarLine->setColor(color);
                  newBarLine->draw(&painter);
                  delete newBarLine;

                  // Draw the current staff name
                  QList<StaffName>& staffNamesLong = currentStaff->part()->instrument()->longNames();
                  QString staffName = staffNamesLong.isEmpty() ? " " : staffNamesLong[0].name();
                  if (staffName == "") {
                        QList<StaffName>& staffNamesShort = currentStaff->part()->instrument()->shortNames();
                        staffName = staffNamesShort.isEmpty() ? "" : staffNamesShort[0].name();
                        }

                  Text* newName = new Text(_score);
                  newName->setXmlText(staffName);
                  newName->setParent(parent);
                  newName->setTrack(e->track());
                  newName->setColor(color);
                  newName->textStyle().setFamily("FreeSans");
                  newName->textStyle().setSizeIsSpatiumDependent(true);
                  newName->layout();
                  newName->setPlainText(newName->plainText());
                  newName->layout();
                  if (currentStaff->part()->staff(0) == currentStaff) {
                        double _spatium = _score->spatium();
                        pos = QPointF (_score->styleP(StyleIdx::clefLeftMargin) + _widthClef, 0 - _spatium * 2);
                        painter.translate(pos);
                        newName->draw(&painter);
                        painter.translate(-pos);
                        }
                  delete newName;

                  // Draw the current Clef
                  Clef* newClef = new Clef(_score);
                  ClefType currentClef = currentStaff->clef(_currentMeasureTick);
                  newClef->setClefType(currentClef);
                  newClef->setParent(parent);
                  newClef->setTrack(e->track());
                  newClef->setColor(color);
                  newClef->layout();
                  pos = QPointF(_score->styleP(StyleIdx::clefLeftMargin), 0);
                  painter.translate(pos);
                  newClef->draw(&painter);
                  pos = QPointF(_widthClef,0);
                  painter.translate(pos);
                  delete newClef;

                  // Draw the current KeySignature
                  KeySig* newKs = new KeySig(_score);
                  KeySigEvent currentKeySigEvent = currentStaff->keySigEvent(_currentMeasureTick);
                  newKs->setKeySigEvent(currentKeySigEvent);

                  // The Parent and the track must be set to have the key signature layout adjusted to different clefs
                  // This also adds naturals to the key signature (if set in the score style)
                  newKs->setParent(parent);
                  newKs->setTrack(e->track());
                  newKs->setColor(color);

                  newKs->setHideNaturals(true);
                  pos = QPointF(_score->styleP(StyleIdx::keysigLeftMargin),0);
                  painter.translate(pos);
                  newKs->layout();
                  newKs->draw(&painter);
                  delete newKs;

                  pos = QPointF(_widthKeySig + _xPosTimeSig, 0);
                  painter.translate(pos);

                  // Draw the current TimeSignature
                  TimeSig* newTs = new TimeSig(_score);

                  // Try to get local time signature, if not, get the current measure one
                  TimeSig* currentTimeSig = currentStaff->timeSig(_currentMeasureTick);
                  if (currentTimeSig) {
                        newTs->setFrom(currentTimeSig);
                        newTs->setParent(parent);
                        newTs->setTrack(e->track());
                        newTs->setColor(color);
                        newTs->layout();
                        pos = QPointF(_score->styleP(StyleIdx::timesigLeftMargin),0);
                        painter.translate(pos);
                        newTs->draw(&painter);
                        delete newTs;
                        }
                  pos = QPointF(_offsetPanel + _widthClef + _widthKeySig + _xPosTimeSig + _leftMarginTotal, e->pagePos().y());
                  painter.translate(-pos);
                  }
            }
      painter.restore();
      }
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QImage PoleFigureImageUtilities::PaintPoleFigureOverlay(int imageWidth, int imageHeight, QString label, QImage image)
{
  int pxHigh = 0;
  int pxWide = 0;

  // Scale the Font Point size to something reasonable to the size of the image. Here our standard was 14Pt Font when the
  // Pole figure was 512 Pixels square.
  int fontPtSize = imageHeight / 32;

  QFont font("Ariel", fontPtSize, QFont::Bold);
  QFontMetrics metrics(font);
  pxHigh = metrics.height();
  pxWide = metrics.width(QString("Y"));

  int pxOffset = 2 * pxWide;
  int pyOffset = 2 * pxHigh;

  int pImageWidth = imageWidth + pxOffset * 2;
  int pImageHeight = imageHeight + pyOffset * 2;

  QImage pImage(pImageWidth, pImageHeight, QImage::Format_ARGB32_Premultiplied);
  pImage.fill(0xFFFFFFFF); // All white background

  // Create a Painter backed by a QImage to draw into
  QPainter painter;
  painter.begin(&pImage);
  painter.setRenderHint(QPainter::Antialiasing, true);
  qint32 penWidth = 1;

#if 0
  // DRAW A BORDER AROUND THE IMAGE FOR DEBUGGING
  QColor c(RgbColor::dRgb(255, 0, 0, 255));
  painter.setPen(QPen(c, penWidth, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin));

  painter.drawLine(0, 0, pImageWidth, 0); // Top
  painter.drawLine(0, 0, 0, pImageHeight); // Left
  painter.drawLine(pImageWidth, 0, pImageWidth, pImageHeight); // Right
  painter.drawLine(0, pImageHeight, pImageWidth, pImageHeight); // Bottom
  //-----------------
#endif

  painter.setFont(font);
//  metrics = painter.fontMetrics();
//  pxHigh = metrics.height();
//  pxWide = metrics.width(QString("Y"));

  // Draw the Pole Figure into the center of the canvas
  QPoint point(pxOffset, pyOffset);
  painter.drawImage(point, image);

  // Scale pen width based on the size of the image
  penWidth = imageHeight / 256;
  painter.setPen(QPen(QColor(0, 0, 0, 255), penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));

  // Draw the Outer circular border around the pole figure
  QPainterPath circle;
  QPointF center(pImageWidth / 2, pImageHeight / 2);
  circle.addEllipse(center, imageWidth / 2, imageHeight / 2);
  painter.drawPath(circle);

  // Label the X Axis
  painter.drawText(pImageWidth - (pxWide * 1.5), pImageHeight / 2 + pxHigh / 3, "X");
  // Label the Y Axis
  pxWide = metrics.width(QString("Y"));
  painter.drawText(pImageWidth / 2 - pxWide / 2, pyOffset - penWidth - 1, "Y");

  // Draw the name of the Pole Figure
  int labelWidth = 0;
  int maxWidth = pImageWidth / 5; // No more than a Quarter of the width of the image
  while(labelWidth < maxWidth)
  {
    fontPtSize++;
    font = QFont("Ariel", fontPtSize, QFont::Bold);
    metrics = QFontMetrics(font);
    labelWidth = metrics.width(label); // Figure out which string is longer (pixel wise)
  }
  painter.setFont(font);
  pxHigh = metrics.height() + 2;
// pxWide = metrics.width(label);
  painter.drawText(pxOffset, pxHigh, label);

  // Draw slightly transparent lines
  //penWidth = 1;
  painter.setPen(QPen(QColor(0, 0, 0, 180), penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
  // Draw the X Axis
  painter.drawLine(pxOffset, pImageHeight / 2, pImageWidth - pxOffset, pImageHeight / 2);
  // Draw the Y Axis
  painter.drawLine(pImageWidth / 2, pyOffset, pImageWidth / 2, pImageHeight - pyOffset);

  painter.end();
  return pImage;
}
Example #7
0
void SigScale::pdraw(QPainter& p, const QRect& r)
{
    int x = r.x();
    int w = r.width();
    int h = height();

    if (x < 0)
        x = 0;
    QColor colTimeLine = QColor(172,181,176);
    p.setPen(colTimeLine);
    p.setFont(QFont("fixed-width", 9, QFont::Bold));
    for (ciSigEvent si = sigmap.begin(); si != sigmap.end(); ++si)
    {
        SigEvent* e = si->second;
        int xp = mapx(e->tick);
        if (xp > x + w)
            break;
        if (xp + 40 < x)
            continue;
        p.drawLine(xp, 0, xp, h / 2);
        p.drawLine(xp, h / 2, xp + 5, h / 2);
        QString s;
        s.sprintf("%d/%d", e->sig.z, e->sig.n);
        p.drawText(xp + 8, h - 6, s);
    }

    //---------------------------------------------------
    //    draw location marker
    //---------------------------------------------------

    //Christopher here is your color
    QList<QColor> colors;
    colors << QColor(0, 186, 255) << QColor(139, 225, 69) << QColor(139, 225, 69) << QColor(156,75,219);
    if (pos[3] != MAXINT)
    {
        p.setPen(colors.at(3));
        int xp = mapx(pos[3]);
        if (xp >= x && xp < x + w)
        {
            p.drawLine(xp, 0, xp, height()-10);
            QPixmap* pm = markIcon[3];
            p.drawPixmap(xp - pm->width() / 2, 1, *pm);
        }
    }

    //colors << QColor(139, 225, 69) << QColor(139, 225, 69) << QColor(0, 186, 255);
    for (int i = 0; i < 3; ++i)
    {
        int xp = mapx(pos[i]);
        if (xp >= x && xp < x + w)
        {
            p.setPen(colors.at(i));
            p.drawLine(xp, 0, xp, 8);
            QPixmap* pm = markIcon[i];
            p.drawPixmap(xp - pm->width() / 2, 1, *pm);
        }
    }
    /*//p.setPen(Qt::red);
    p.setPen(QColor(0, 186, 255));
    int xp = mapx(pos[0]);
    if (xp >= x && xp < x + w)
        p.drawLine(xp, 0, xp, h);
    //p.setPen(Qt::blue);
    p.setPen(QColor(139, 225, 69));
    xp = mapx(pos[1]);
    if (xp >= x && xp < x + w)
        p.drawLine(xp, 0, xp, h);
    xp = mapx(pos[2]);
    if (xp >= x && xp < x + w)
        p.drawLine(xp, 0, xp, h);*/
}
void NavigationMapObject::paint(QPainter &painter, QRect view, int scale)
{
	// Save the painter state for this paint session
	// so that it can be restored after without influencing other objects
	painter.save(); {

		// Translate, scale, and rotate...
		QTransform t;
		t.scale(1.0/scale, 1.0/scale);
		t.translate(x - view.x()*scale, view.height()*scale - y + view.y()*scale);
		painter.setTransform(t, true);

		if(navigation != NULL) {

			// Init
			QColor pink(255,68,224);
			width = 0;
			height = 0;
			painter.setPen(Qt::transparent);
			painter.setOpacity(0.5);
			painter.setBrush(QBrush(pink));
			QList<Vector2D> navPoints = navigation->getNavPoints();

			// Draw all nav points
			for(int i = 0; i < navPoints.count(); i++) {

				// Calc size and coord
				int size = 100;
				if(navigation->getCurrentNavPoint()+1 == i) size = 200;
				int x = (int)navPoints.at(i).x();
				int y = (int)navPoints.at(i).y();

				// Set object dimensions based on most distant points...
				if(x > width) width = x;
				if(y > height) height = y;

				painter.setPen(Qt::transparent);
				painter.setOpacity(0.5);
				painter.setBrush(QBrush(pink));
				painter.drawEllipse(QRect(x - (size / 2), (-y) - (size / 2), size, size));

				painter.setFont(QFont("Arial Black", 120, QFont::Bold));
				painter.setPen(pink);
				painter.setOpacity(0.5);
				painter.drawText(x + 150, (-y) - 150, QString("%1").arg(i));

				if(i > 0) {

					QPen pen = painter.pen();
					pen.setWidth(20);
					painter.setPen(pen);
					painter.drawLine((int)navPoints.at(i-1).x(), -((int)navPoints.at(i-1).y()), x, -y);
				}
			}

			// Draw splines
			if(navigation->name == "SplineNavigation") {
//				drawSpline(painter, ((SplineNavigation*)navigation)->getNavSplineX(), ((SplineNavigation*)navigation)->getNavSplineY(), scale, Qt::yellow, 20);
//				drawSpline(painter, ((SplineNavigation*)navigation)->getWheelLeftSplineX(), ((SplineNavigation*)navigation)->getWheelLeftSplineY(), scale, Qt::red, 1);
//				drawSpline(painter, ((SplineNavigation*)navigation)->getWheelRightSplineX(), ((SplineNavigation*)navigation)->getWheelRightSplineY(), scale, Qt::green, 1);
			}

		}

	} painter.restore();
}
Example #9
0
void QgsGrassEdit::displayIcon( double x, double y, const QPen & pen,
                                int type, int size, QPainter *painter )
{
  QgsPoint point;
  QPolygon pointArray( 2 );

  point.setX( x );
  point.setY( y );

  point = transformLayerToCanvas( point );

  int px = qRound( point.x() );
  int py = qRound( point.y() );
  int m = ( size - 1 ) / 2;

  QPainter *myPainter;
  if ( !painter )
  {
    myPainter = new QPainter();
    myPainter->begin( mPixmap );
  }
  else
  {
    myPainter = painter;
  }

  myPainter->setPen( pen );

  switch ( type )
  {
    case QgsVertexMarker::ICON_CROSS :
      pointArray.setPoint( 0, px - m, py );
      pointArray.setPoint( 1, px + m, py );
      myPainter->drawPolyline( pointArray );

      pointArray.setPoint( 0, px, py + m );
      pointArray.setPoint( 1, px, py - m );
      myPainter->drawPolyline( pointArray );
      break;
    case QgsVertexMarker::ICON_X :
      pointArray.setPoint( 0, px - m, py + m );
      pointArray.setPoint( 1, px + m, py - m );
      myPainter->drawPolyline( pointArray );

      pointArray.setPoint( 0, px - m, py - m );
      pointArray.setPoint( 1, px + m, py + m );
      myPainter->drawPolyline( pointArray );
      break;
    case QgsVertexMarker::ICON_BOX :
      pointArray.resize( 5 );
      pointArray.setPoint( 0, px - m, py - m );
      pointArray.setPoint( 1, px + m, py - m );
      pointArray.setPoint( 2, px + m, py + m );
      pointArray.setPoint( 3, px - m, py + m );
      pointArray.setPoint( 4, px - m, py - m );
      myPainter->drawPolyline( pointArray );
      break;
  }

  if ( !painter )
  {
    myPainter->end();
    //mCanvas->update();
    mCanvasEdit->update();
    delete myPainter;
  }
}
Example #10
0
bool FunctionalTest::Draw(QPainter& painter, QRect &free_rect , const QString &) const
{
    test::hydro_cylinder::Parameters *params = static_cast< test::hydro_cylinder::Parameters * >( CURRENT_PARAMS );
    if ( !params )
        return true;

    QFont header_font = painter.font();
    header_font.setFamily("Arial");
    header_font.setPointSize( 14 );
    QFont result_font = header_font;
    result_font.setUnderline(true);
    QFont text_font = header_font;
    text_font.setPointSize( 12 );


    auto DrawRowCenter = [ &painter, &free_rect ](QRect const& place, QFont const& font, QColor const& color, QString const& text )
    {
        painter.save();
        QFontMetrics metrix( font );
        QPoint start_point( place.center().x() - metrix.width( text ) / 2, place.center().y() +metrix.height()/2);
        painter.setFont( font );
        painter.setPen( color );
        painter.drawText( start_point, text );
        painter.restore();
    };
    auto DrawRowLeft = [ &painter, &free_rect ](    QRect const& place,
                                                    QFont const& font,
                                                    QColor const& color1,
                                                    QString const& label,
                                                    QColor const& color2 = Qt::black,
                                                    QString const& value = "",
                                                    QColor const& color3 = Qt::black,
                                                    QString const& value2 = "")
    {
        painter.save();
        QFontMetrics metrix( font );
        QPoint start_point( place.left() , place.center().y()+metrix.height()/2 );
        QPoint start_point2( start_point.x() + metrix.width(label), place.center().y() +metrix.height()/2);
        QPoint start_point3( start_point2.x() + metrix.width(value), place.center().y() +metrix.height()/2);
        painter.setFont( font );
        painter.setPen( color1 );
        painter.drawText( start_point, label );
        painter.setPen( color2 );
        painter.drawText( start_point2, value );
        painter.setPen( color3 );
        painter.drawText( start_point3, value2 );
        painter.restore();
    };

    QFontMetrics m(text_font);
    int width = m.width("123456789012345678901234567890123456789012345");
    char symbol = '.';
    auto FillToSize = [ width, &m, symbol ]( QString text )
    {
        while( m.width( text + symbol ) < width )
            text += symbol;
        return text + " ";
    };


    uint32_t num = 0;
    bool res = DrawLine( num, free_rect, result_font,
    [ this, &painter, &DrawRowCenter, &result_font ]( QRect const& rect )
    {
        DrawRowCenter( rect, result_font, Qt::black, "Результаты испытаний" );
    }, 2 );

    res = DrawLine( num, free_rect, text_font,
    [ this, &painter, &DrawRowLeft, &FillToSize, &text_font ]( QRect const& rect )
    {
        DrawRowLeft( rect, text_font, Qt::black, FillToSize("Температура масла во время испытаний, ˚С"), Qt::red, test::ToString(OilTemp) );
    }, 2 );


    QString header = "<html>"
            "<head>"
              "<meta charset='utf-8'>"
              "<style type='text/css'>"
                   "td { text-align: center;}"
                   "th { font-weight: normal; padding: 2px;}"
                   "table {border-collapse: collapse; border-style: solid; vertical-align:middle;}"
             "</style>"
            "</head>"
            "<body>"
            "<table width='100%' border='1.5' cellspacing='-0.5' cellpadding='-0.5'>"
               "<tr>"
                   "<th> Номер </th>"
                   "<th></th>"
                   "<th> Работоспособность </th>"
               "</tr>";

    QString footer = "</table>"
            "</body>"
            "</html>";

    typedef std::pair<QString, bool> Item;
    std::vector< Item > tests;
    tests.push_back( Item( "Наружная герметичность ", HermResult ) );
    tests.push_back( Item( "Максимальное давление", MaxPressureResult ) );
    tests.push_back( Item( "Рабочее давление", WorkPressureResult ) );
    tests.push_back( Item( "Номинальный расход", ExpenditureResult ) );
    tests.push_back( Item( "Время перемещения в одну сторону", MoveTimeResult ) );

    QString rows;
    for ( size_t i =  1, end = tests.size(); i <= end; ++i )
    {
        Item& data = tests[i-1];
        rows +=  "<tr>"
                   "<td>"+test::ToString( static_cast<int>(i) )+"</td>"
                   "<td>"+ data.first +"</td>"
                   "<td style='font-size:28pt; color: \"red\"; font-weight:bold;'>"+ (data.second ? QString("+"):QString("-")) +"</td>"
                "</tr>";
    }

    QString table = header + rows + footer;


    QTextDocument doc;
    doc.setUndoRedoEnabled( false );
    doc.setTextWidth( free_rect.width() );
    doc.setUseDesignMetrics( true );
    doc.setDefaultTextOption ( QTextOption (Qt::AlignHCenter )  );
    doc.setHtml( table );
    auto h = doc.documentLayout()->documentSize().height();

    res = DrawLine( num, free_rect, text_font,
    [ this, &painter, &doc, &text_font ]( QRect const& rect )
    {
        painter.save();
        QRectF r( 0, 0, rect.width(), rect.height() );
        painter.translate( rect.topLeft() );
        doc.drawContents( &painter, r);
        painter.restore();
    }, 1, h );

    res = DrawLine( num, free_rect, header_font,
    [ this, &painter, &DrawRowLeft, &header_font ]( QRect const& rect )
    {
        DrawRowLeft( rect, header_font, Qt::black, "ИТОГ:" );
    }, 1.5 );

    res = DrawLine( num, free_rect, text_font,
    [ this, &painter, &DrawRowLeft, &text_font, params ]( QRect const& rect )
    {
        DrawRowLeft( rect, text_font,   Qt::black, "Гидроцилиндр ",
                                        Qt::red, params->SerNo() + (Success()? QString(" годен ") : QString(" не годен ")),
                                        Qt::black, " к эксплуатации");
    }, 3 );
    return res;
}
Example #11
0
void StickyNoteActor::syncStickyNoteWithFileContents()
{
	reauthorize(false);

	// clear the old texture
#ifdef DXRENDER
	SAFE_RELEASE(_stickyNoteTextureId);
#else
	if (_stickyNoteTextureId)
	{
		glDeleteTextures(1, &_stickyNoteTextureId);
		_stickyNoteTextureId = 0;
	}
#endif

	// get the font
	int fontSize = NxMath::max(20, themeManager->getValueAsInt("ui.stickyNote.font.size",0));
	FontDescription desc(themeManager->getValueAsFontFamilyName("ui.stickyNote.font.family",""), fontSize);
	QFont stickyNoteFont = fontManager->getFont(desc);

	// get the sticky note text
	QString stickyNoteStr;
	getStickyNote(getFullPath(), &stickyNoteStr);

	// layout the sticky note text
	QTextOption option;
		option.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
	_stickyNoteText.setDefaultTextOption(option);
	_stickyNoteText.setDefaultFont(stickyNoteFont);
	_stickyNoteText.setDocumentMargin(12.5f);
	_stickyNoteText.setTextWidth(256);
	_stickyNoteText.setPlainText(stickyNoteStr);

	QSizeF textSize = _stickyNoteText.size();
	const int minStickyNoteFontSize = 10;
	while (textSize.height() > 256 && 
		   stickyNoteFont.pointSize() > minStickyNoteFontSize)
	{
		stickyNoteFont.setPointSize(stickyNoteFont.pointSize() - 1);
		_stickyNoteText.setDefaultFont(stickyNoteFont);
		textSize = _stickyNoteText.size();
	}

	// render the sticky note to a qimage
	const unsigned int bufferSize = 256;
	QImage image(bufferSize, bufferSize, QImage::Format_ARGB32);
	image.fill(Qt::red);
	QPainter p;
	p.begin(&image);
	p.setRenderHint(QPainter::Antialiasing, true);
	p.setRenderHint(QPainter::TextAntialiasing, true);
		p.drawImage(0, 0, _stickyNoteBackground);
		p.setPen(QColor(50, 50, 75));
		_stickyNoteText.drawContents(&p, QRect(0, 0, bufferSize, int(bufferSize - _stickyNoteText.documentMargin())));
	p.end();
#ifdef DXRENDER
	_stickyNoteTextureId = dxr->createTextureFromData(image.width(), image.height(), image.bits(), image.bytesPerLine());
#else
	// load the qimage into open gl
	glGenTextures(1, &_stickyNoteTextureId);
	glBindTexture(GL_TEXTURE_2D, _stickyNoteTextureId);

	float maximumAnisotropy = 0.0f;
	glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maximumAnisotropy);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, maximumAnisotropy);
	if (GLEW_ARB_texture_border_clamp)
	{
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER_ARB);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER_ARB);
	}
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);

	// copy the full image (glTexSubImage2D does not work well with GL_GENERATE_MIPMAP)
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width(), image.height(),
		0, GL_BGRA, GL_UNSIGNED_BYTE, image.bits());
#endif
}
void SpeechAudiometryWidget::drawData()
{
    int xx = -1;
    int yy = -1;

    QPainter paint;
    paint.begin(&m_data);

    // Draw RE data
    paint.setPen(Qt::red);
    xx = -1;
    yy = -1;
    for (int i = 0; i < 23; ++i)
    {
        int x = BORDER_LEFT + i*gridWidth()/22;
        if (m_reData[i] >= 0)
        {
            int y = BORDER_TOP + static_cast<int> (((100 - m_reData[i])/100.0)*gridHeight() + 0.5);
            switch (m_kind)
            {
                case WITHOUT:
                    paint.drawEllipse(x-4, y-4, 8, 8);
                    break;
                case WITH:
                    paint.setBrush(QBrush(paint.pen().color(), Qt::SolidPattern));
                    paint.drawEllipse(x-4, y-4, 8, 8);
                    paint.setBrush(Qt::NoBrush);
                    break;
                default:
                   Q_ASSERT(false);
            }
            if (xx > 0 && yy > 0) paint.drawLine(xx, yy, x, y);
            xx = x;
            yy = y;
        }
    }

    // Draw LE data
    paint.setPen(Qt::blue);
    xx = -1;
    yy = -1;
    for (int i = 0; i < 23; ++i)
    {
        int x = BORDER_LEFT + i*gridWidth()/22;
        if (m_leData[i] >= 0)
        {
            int y = BORDER_TOP + static_cast<int> (((100 - m_leData[i])/100.0)*gridHeight() + 0.5);
            switch (m_kind)
            {
                case WITHOUT:
                    paint.drawLine(x-4, y-4, x+4, y+4);
                    paint.drawLine(x-4, y+4, x+4, y-4);
                    break;
                case WITH:
                    paint.fillRect(x-4, y-4, 8, 8, paint.pen().color());
                    break;
                default:
                   Q_ASSERT(false);
            }
            if (xx > 0 && yy > 0) paint.drawLine(xx, yy, x, y);
            xx = x;
            yy = y;
        }
    }

    // Draw RELE data
    paint.setPen(Qt::darkGreen);
    xx = -1;
    yy = -1;
    for (int i = 0; i < 23; ++i)
    {
        int x = BORDER_LEFT + i*gridWidth()/22;
        if (m_releData[i] >= 0)
        {
            int y = BORDER_TOP + static_cast<int> (((100 - m_releData[i])/100.0)*gridHeight() + 0.5);
            switch (m_kind)
            {
                case WITHOUT:
                    paint.drawLine(x-4, y+4, x+4, y+4);
                    paint.drawLine(x-4, y+4, x, y-4);
                    paint.drawLine(x, y-4, x+4, y+4);
                    break;
                case WITH:
                    {
                        paint.setBrush(QBrush(paint.pen().color(), Qt::SolidPattern));
                        QPoint points[] = { QPoint(x-4, y+4), QPoint(x+4, y+4), QPoint(x, y-4) };
                        paint.drawConvexPolygon(points, 3);
                        paint.setBrush(Qt::NoBrush);
                    }
                    break;
                default:
                   Q_ASSERT(false);
            }
            if (xx > 0 && yy > 0) paint.drawLine(xx, yy, x, y);
            xx = x;
            yy = y;
        }
    }
}
void SpeechAudiometryWidget::drawGrid()
{
    QPainter paint;
    paint.begin(&m_rooster);

    QFont boldFont;
    boldFont.setBold(true);

    // Paint the vertical axes
    for (int i = 0; i < 23; ++i)
    {
        int x = BORDER_LEFT + i*gridWidth()/22;
        paint.setPen(Qt::black);
        if ((i % 2 == 0) && (i != 0) && (i < 20))
            paint.drawText(x-6, gridHeight()+25, QString::number(i*5));
        else if (i == 20)
            paint.drawText(x-9, gridHeight()+25, QString::number(i*5));

        paint.setPen(QPen((i == 0 || i == 8 || i == 11 || i == 14) ? Qt::black : Qt::lightGray, (i == 0) ? 2 : 1));
        paint.drawLine(x, BORDER_TOP, x, gridHeight()+BORDER_TOP);
    }
    paint.setPen(Qt::black);
    paint.setFont(boldFont);
    paint.drawText(BORDER_LEFT+gridWidth(), 25+gridHeight(), "dB");
    paint.setFont(QFont());

    // Paint the horizontal axes
    for (int i = 0; i < 21; ++i)
    {
        int y = BORDER_TOP + i*gridHeight()/20;
        if (i % 2 == 0)
        {
            paint.setPen(Qt::black);
            paint.drawText(15 + 6*((i/20) + (i == 0 ? 0 : 1)), y+6, QString::number((20-i)*5));
        }

        paint.setPen(QPen((i == 10 || i == 20) ? Qt::black : Qt::lightGray, (i == 20) ? 2 : 1));
        paint.drawLine(BORDER_LEFT+1, y, BORDER_LEFT+gridWidth(), y);
    }
    paint.setPen(Qt::black);
    paint.setFont(boldFont);
    paint.drawText(34, 8, "%");
    paint.setFont(QFont());

    // Tekenen van de curve
    int minY = BORDER_TOP;
    int maxY = BORDER_TOP + gridHeight();
    paint.setPen(Qt::black);
    for (int x = BORDER_LEFT; x < BORDER_LEFT + 2*(gridWidth()/22); ++x)
    {
        double xx1 = (x - BORDER_LEFT*1.0) / (4.0*(gridWidth()/22.0) / 20.0);
        double yy1 = (3.0/5.0)*xx1*xx1 - xx1;
        double xx2 = (x - BORDER_LEFT*1.0 + 1.0) / (4.0*(gridWidth()/22.0) / 20.0);
        double yy2 = (3.0/5.0)*xx2*xx2 - xx2;
        int y1 = std::min(static_cast<int> (BORDER_TOP + ((100.0 - yy1) * gridHeight())/100.0), maxY);
        int y2 = std::min(static_cast<int> (BORDER_TOP + ((100.0 - yy2) * gridHeight())/100.0), maxY);
        paint.drawLine(x, y1, x+1, y2);
    }
    for (int x = BORDER_LEFT + 2*(gridWidth()/22); x < BORDER_LEFT + 4*(gridWidth()/22); ++x)
    {
        double xx1 = (x - BORDER_LEFT*1.0) / (4.0*(gridWidth()/22.0) / 20.0);
        double yy1 = (-3.0/5.0)*xx1*xx1 + 23.0*xx1 - 120.0;
        double xx2 = (x - BORDER_LEFT*1.0 + 1.0) / (4.0*(gridWidth()/22.0) / 20.0);
        double yy2 = (-3.0/5.0)*xx2*xx2 + 23.0*xx2 - 120.0;
        int y1 = std::max(static_cast<int> (BORDER_TOP + ((100.0 - yy1) * gridHeight())/100.0), minY);
        int y2 = std::max(static_cast<int> (BORDER_TOP + ((100.0 - yy2) * gridHeight())/100.0), minY);
        paint.drawLine(x, y1, x+1, y2);
    }
}
void QgsEllipseSymbolLayerV2::renderPoint( const QPointF& point, QgsSymbolV2RenderContext& context )
{
  bool ok;
  if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_OUTLINE_WIDTH ) )
  {
    context.setOriginalValueVariable( mOutlineWidth );
    double width = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_OUTLINE_WIDTH, context, mOutlineWidth ).toDouble();
    width = QgsSymbolLayerV2Utils::convertToPainterUnits( context.renderContext(), width, mOutlineWidthUnit, mOutlineWidthMapUnitScale );
    mPen.setWidthF( width );
  }
  if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_OUTLINE_STYLE ) )
  {
    context.setOriginalValueVariable( QgsSymbolLayerV2Utils::encodePenStyle( mPen.style() ) );
    QString styleString = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_OUTLINE_STYLE, context, QVariant(), &ok ).toString();
    if ( ok )
    {
      Qt::PenStyle style = QgsSymbolLayerV2Utils::decodePenStyle( styleString );
      mPen.setStyle( style );
    }
  }
  if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_FILL_COLOR ) )
  {
    context.setOriginalValueVariable( QgsSymbolLayerV2Utils::encodeColor( mBrush.color() ) );
    QString colorString = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_FILL_COLOR, context, QVariant(), &ok ).toString();
    if ( ok )
      mBrush.setColor( QgsSymbolLayerV2Utils::decodeColor( colorString ) );
  }
  if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_OUTLINE_COLOR ) )
  {
    context.setOriginalValueVariable( QgsSymbolLayerV2Utils::encodeColor( mPen.color() ) );
    QString colorString = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_OUTLINE_COLOR, context, QVariant(), &ok ).toString();
    if ( ok )
      mPen.setColor( QgsSymbolLayerV2Utils::decodeColor( colorString ) );
  }
  double scaledWidth = mSymbolWidth;
  double scaledHeight = mSymbolHeight;
  if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_WIDTH ) || hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_HEIGHT ) || hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_SYMBOL_NAME ) )
  {
    QString symbolName =  mSymbolName;
    if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_SYMBOL_NAME ) )
    {
      context.setOriginalValueVariable( mSymbolName );
      symbolName = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_SYMBOL_NAME, context, mSymbolName ).toString();
    }
    preparePath( symbolName, context, &scaledWidth, &scaledHeight, context.feature() );
  }

  //offset
  double offsetX = 0;
  double offsetY = 0;
  markerOffset( context, scaledWidth, scaledHeight, mSymbolWidthUnit, mSymbolHeightUnit, offsetX, offsetY, mSymbolWidthMapUnitScale, mSymbolHeightMapUnitScale );
  QPointF off( offsetX, offsetY );

  QPainter* p = context.renderContext().painter();
  if ( !p )
  {
    return;
  }

  //priority for rotation: 1. data defined symbol level, 2. symbol layer rotation (mAngle)
  double rotation = 0.0;
  if ( hasDataDefinedProperty( QgsSymbolLayerV2::EXPR_ROTATION ) )
  {
    context.setOriginalValueVariable( mAngle );
    rotation = evaluateDataDefinedProperty( QgsSymbolLayerV2::EXPR_ROTATION, context, mAngle ).toDouble() + mLineAngle;
  }
  else if ( !qgsDoubleNear( mAngle + mLineAngle, 0.0 ) )
  {
    rotation = mAngle + mLineAngle;
  }
  if ( rotation )
    off = _rotatedOffset( off, rotation );

  QMatrix transform;
  transform.translate( point.x() + off.x(), point.y() + off.y() );
  if ( !qgsDoubleNear( rotation, 0.0 ) )
  {
    transform.rotate( rotation );
  }

  p->setPen( mPen );
  p->setBrush( mBrush );
  p->drawPath( transform.map( mPainterPath ) );
}
Example #15
0
    void MapControl::paintEvent(QPaintEvent* evnt)
    {
        Q_UNUSED(evnt);

        static QPixmap *doubleBuffer( new QPixmap(width(), height()) );

        //check for resize change
        if ( doubleBuffer->width() != width() || doubleBuffer->height() != height() )
        {
            delete doubleBuffer;
            doubleBuffer = new QPixmap(width(), height());
        }

        QPainter dbPainter;
        dbPainter.begin(doubleBuffer);

        layermanager->drawImage(&dbPainter);
        layermanager->drawGeoms(&dbPainter);

        // draw scale
        if (scaleVisible)
        {
            static QList<double> distanceList;
            if (distanceList.isEmpty())
            {
                distanceList<<5000000<<2000000<<1000000<<1000000<<1000000<<100000<<100000<<50000<<50000<<10000<<10000<<10000<<1000<<1000<<500<<200<<100<<50<<25;
            }

            if (currentZoom() >= layermanager->minZoom() && distanceList.size() > currentZoom())
            {
                double line;
                line = distanceList.at( currentZoom() ) / pow(2.0, 18-currentZoom() ) / 0.597164;

                // draw the scale
                dbPainter.setPen(Qt::black);
                QPoint p1(10,size.height()-20);
                QPoint p2((int)line,size.height()-20);
                dbPainter.drawLine(p1,p2);

                dbPainter.drawLine(10,size.height()-15, 10,size.height()-25);
                dbPainter.drawLine((int)line,size.height()-15, (int)line,size.height()-25);

                QString distance;
                if (distanceList.at(currentZoom()) >= 1000)
                {
                    distance = QVariant( distanceList.at(currentZoom())/1000 )  .toString()+ " km";
                }
                else
                {
                    distance = QVariant( distanceList.at(currentZoom()) ).toString() + " m";
                }

                dbPainter.drawText(QPoint((int)line+10,size.height()-15), distance);
            }
        }

        if (crosshairsVisible)
        {
            dbPainter.drawLine(screen_middle.x(), screen_middle.y()-10,
                             screen_middle.x(), screen_middle.y()+10); // |
            dbPainter.drawLine(screen_middle.x()-10, screen_middle.y(),
                             screen_middle.x()+10, screen_middle.y()); // -
        }

        dbPainter.drawRect(0,0, size.width(), size.height());

        if (mousepressed && mymousemode == Dragging)
        {
            QRect rect = QRect(pre_click_px, current_mouse_pos);
            dbPainter.drawRect(rect);
        }
        dbPainter.end();
        QPainter painter;
        painter.begin( this );
        painter.drawPixmap( rect(), *doubleBuffer, doubleBuffer->rect() );
        painter.end();
    }
Example #16
0
	void ContactListDelegate::DrawContact (QPainter *painter,
			QStyleOptionViewItemV4 option, const QModelIndex& index) const
	{
		QObject *entryObj = index.data (Core::CLREntryObject).value<QObject*> ();
		ICLEntry *entry = qobject_cast<ICLEntry*> (entryObj);

		const bool isMUC = entry->GetEntryType () == ICLEntry::ETMUC;

		QStyle *style = option.widget ?
				option.widget->style () :
				QApplication::style ();

		const QRect& r = option.rect;
		const int sHeight = r.height ();
		const int iconSize = sHeight - 2 * CPadding;

		const QIcon& stateIcon = index.data (Qt::DecorationRole).value<QIcon> ();
		QString name = index.data (Qt::DisplayRole).value<QString> ();
		const QString& status = entry->GetStatus ().StatusString_;
		const QImage& avatarImg = ShowAvatars_ ?
				Core::Instance ().GetAvatar (entry, iconSize) :
				QImage ();
		const int unreadNum = index.data (Core::CLRUnreadMsgCount).toInt ();
		const QString& unreadStr = unreadNum ?
				QString (" %1 :: ").arg (unreadNum) :
				QString ();
		if (!status.isEmpty ())
			name += " (" + status + ")";

		const bool selected = option.state & QStyle::State_Selected;
		const QColor fgColor = selected ?
				option.palette.color (QPalette::HighlightedText) :
				option.palette.color (QPalette::Text);

		QFont unreadFont;
		int unreadSpace = 0;
		if (unreadNum)
		{
			unreadFont = option.font;
			unreadFont.setBold (true);

			unreadSpace = CPadding + QFontMetrics (unreadFont).width (unreadStr);
		}

		const int textShift = 2 * CPadding + iconSize + unreadSpace;

		const QList<QIcon>& clientIcons = isMUC || !ShowClientIcons_ ?
				QList<QIcon> () :
				Core::Instance ().GetClientIconForEntry (entry).values ();
		const int clientsIconsWidth = isMUC|| !ShowClientIcons_ ?
				0 :
				clientIcons.size () * (iconSize + CPadding) - CPadding;
		/* text for width is total width minus shift of the text from
		 * the left (textShift) minus space for avatar (if present) with
		 * paddings minus space for client icons and paddings between
		 * them: there are N-1 paddings inbetween if there are N icons.
		 */
		const int textWidth = r.width () - textShift -
				(isMUC || !ShowAvatars_ ? 0 : (iconSize + 2 * CPadding)) -
				clientsIconsWidth;

		QPixmap pixmap (r.size ());
		pixmap.fill (Qt::transparent);
		QPainter p (&pixmap);
		p.translate (-r.topLeft ());

		if (selected ||
				(option.state & QStyle::State_MouseOver))
			style->drawPrimitive (QStyle::PE_PanelItemViewItem,
					&option, &p, option.widget);

		p.setPen (fgColor);

		if (unreadNum)
		{
			p.setFont (unreadFont);
			p.drawText (r.left () + textShift - unreadSpace, r.top () + CPadding,
					textWidth, r.height () - 2 * CPadding,
					Qt::AlignVCenter | Qt::AlignLeft,
					unreadStr);
		}

		p.setFont (option.font);
		p.drawText (r.left () + textShift, r.top () + CPadding,
				textWidth, r.height () - 2 * CPadding,
				Qt::AlignVCenter | Qt::AlignLeft,
				option.fontMetrics.elidedText (name, Qt::ElideRight, textWidth));

		p.drawPixmap (r.topLeft () + QPoint (CPadding, CPadding),
				stateIcon.pixmap (iconSize, iconSize));

		if (!avatarImg.isNull ())
			p.drawPixmap (r.topLeft () + QPoint (textShift + textWidth + clientsIconsWidth + CPadding, CPadding),
					QPixmap::fromImage (avatarImg));

		int currentShift = textShift + textWidth + CPadding;
		Q_FOREACH (const QIcon& icon, clientIcons)
		{
			p.drawPixmap (r.topLeft () + QPoint (currentShift, CPadding),
					icon.pixmap (iconSize, iconSize));
			currentShift += iconSize + CPadding;
		}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QImage PoleFigureImageUtilities::GenerateScalarBar(int imageWidth, int imageHeight, PoleFigureConfiguration_t& config)
{
  int numColors = config.numColors;
  QImage pImage(imageWidth, imageHeight, QImage::Format_ARGB32_Premultiplied);
  pImage.fill(0xFFFFFFFF); // All white background

  // Create a Painter backed by a QImage to draw into
  QPainter painter;
  painter.begin(&pImage);
  painter.setRenderHint(QPainter::Antialiasing, true);

  int penWidth = 1;

#if 0
  // DRAW A BORDER AROUND THE IMAGE FOR DEBUGGING
  QColor c(RgbColor::dRgb(255, 0, 0, 255));
  painter.setPen(QPen(c, penWidth, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin));

  painter.drawLine(0, 0, imageWidth, 0); // Top
  painter.drawLine(0, 0, 0, imageHeight); // Left
  painter.drawLine(imageWidth, 0, imageWidth, imageHeight); // Right
  painter.drawLine(0, imageHeight, imageWidth, imageHeight); // Bottom
  //-----------------
#endif

  //Get all the colors that we will need
  QVector<DREAM3D::Rgb> colorTable(numColors);
  QVector<float> colors(3 * numColors, 0.0);
  DREAM3DColorTable::GetColorTable(numColors, colors); // Generate the color table values
  float r = 0.0, g = 0.0, b = 0.0;
  for (int i = 0; i < numColors; i++) // Convert them to QRgbColor values
  {
    r = colors[3 * i];
    g = colors[3 * i + 1];
    b = colors[3 * i + 2];
    colorTable[i] = RgbColor::dRgb(r * 255, g * 255, b * 255, 255);
  }

  // Now start from the bottom and draw colored lines up the scale bar
  // A Slight Indentation for the scalar bar
  float margin = 0.05f;
  float scaleBarRelativeWidth = 0.10f;
  float scaleBarRelativeHeight = 1.0f - (margin * 2);

  int colorHeight = int( (imageHeight * scaleBarRelativeHeight) / numColors);

  QPointF topLeft(imageWidth * margin, imageHeight * margin);
  QSizeF size(imageWidth * scaleBarRelativeWidth, imageHeight * scaleBarRelativeHeight);

  int yLinePos = topLeft.y();

  QPointF start = topLeft;
  QPointF end = topLeft;

  for(int i = numColors - 1; i >= 0; i--)
  {
    QColor c(colorTable[i]);
    painter.setPen(QPen(c, penWidth, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin));
    for(int j = 0; j < colorHeight; j++)
    {
      start.setY(yLinePos);
      end.setX(topLeft.x() + (imageWidth * scaleBarRelativeWidth));
      end.setY(yLinePos);
      painter.drawLine(start, end);
      yLinePos++;
    }
  }

  // Draw the border of the scale bar
  size = QSizeF(imageWidth * scaleBarRelativeWidth, numColors * colorHeight); // Add two pixel to the height so we don't over write part of the scale bar
  QRectF scaleBorder(topLeft, size);
  penWidth = 2;
  painter.setPen(QPen(QColor(0, 0, 0, 255), penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
  painter.drawRect(scaleBorder);


  // Draw the Text Labels of the Scale Bar
  int startFontPtSize = 10;
  QFont font("Ariel", startFontPtSize, QFont::Bold);

  QFontMetrics metrics(font);
  int fontPixelsHeight = metrics.height();
  while(fontPixelsHeight < colorHeight * 2)
  {
    startFontPtSize++;
    font = QFont("Ariel", startFontPtSize, QFont::Bold);
    metrics = QFontMetrics(font);
    fontPixelsHeight = metrics.height();
  }
  painter.setFont(font);

  // Draw some more information to the right of the Scale Bar
  QString maxStr = QString::number(config.maxScale, 'f', 3);
  painter.drawText(topLeft.x() + (imageWidth * scaleBarRelativeWidth) + 10, topLeft.y() + fontPixelsHeight, maxStr);

  QString minStr = QString::number(config.minScale, 'f', 3);
  painter.drawText(topLeft.x() + (imageWidth * scaleBarRelativeWidth) + 10, topLeft.y() + size.height(), minStr);
  //------------------------------


  // Draw some statistics for the pole figures
  startFontPtSize = 8; // Set it to a rather large point size so we can fit the text perfectly. Only an insanely large Polefigure would go past this size
  int labelWidth = 0;

  // Make sure the size of font we just picked will allow the string to NOT be clipped because the rendered
  // pixel width is past the right side of the image
  int endOfStringYPos = topLeft.x() + (imageWidth * scaleBarRelativeWidth) + 10 + labelWidth;
  while(endOfStringYPos < imageWidth)
  {
    startFontPtSize++;
    font = QFont("Ariel", startFontPtSize, QFont::Bold);
    metrics = QFontMetrics(font);
    QString label("Upper & Lower");
    QString label2 = QString("Samples: ") + QString::number(config.eulers->getNumberOfTuples());
    fontPixelsHeight = metrics.height(); // Update the font height
    int labelWidth = metrics.width(label); // Figure out which string is longer (pixel wise)
    if (labelWidth < metrics.width(label2))
    {
      labelWidth = metrics.width(label2);
    }
    endOfStringYPos = topLeft.x() + (imageWidth * scaleBarRelativeWidth) + 10 + labelWidth;
  }
  startFontPtSize--;
  font = QFont("Ariel", startFontPtSize, QFont::Bold);
  metrics = QFontMetrics(font);
  QString label("Upper & Lower");
  QString label2 = QString("Samples: ") + QString::number(config.eulers->getNumberOfTuples());

  labelWidth = metrics.width(label);
  if (labelWidth < metrics.width(label2))
  {
    labelWidth = metrics.width(label2);
  }

  // Set the font into the Painter
  painter.setFont(font);

  QPointF statsPoint(topLeft.x() + (imageWidth * scaleBarRelativeWidth) + 10, imageHeight * .5);

  // Draw some more Statistics Text
  painter.drawText(statsPoint, label);
  statsPoint.setY(imageHeight * .5 + fontPixelsHeight);
  painter.drawText(statsPoint, label2);

  painter.end();
  // Scale the image down to 225 pixels
  return pImage;

}
Example #18
0
void UserViewDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    UserViewItemBase *base = dynamic_cast<UserViewItemBase*>(m_uv->itemFromIndex(index));
    if( NULL == base )
        return;

    painter->save();
    painter->translate(option.rect.x(), option.rect.y());

    QPainter *p = painter;
    QPalette cg = option.palette;
    int width = option.rect.width();
    int height = option.rect.height();
    QSize itemsize = option.rect.size();
    int margin = 1;

    switch( base->type() )
    {
    case GRP_ITEM:
        {
            GroupItem *item = static_cast<GroupItem*>(base);
            QString text = index.data( Qt::DisplayRole ).toString();
            QImage img = Image( ( option.state & QStyle::State_Open ) ? "expanded" : "collapsed");
            if (!img.isNull())
                p->drawImage(2 + margin, (height - img.height()) / 2, img);
            int x = 24 + margin;
            if (!( option.state & QStyle::State_Open ) && item->m_unread)
            {
                CommandDef *lcmdDefUnreadMessages = CorePlugin::instance()->messageTypes.find(item->m_unread);
                if (lcmdDefUnreadMessages)
                {
                    img = Image(lcmdDefUnreadMessages->icon);
                    if (!img.isNull())
                    {
                        if (m_uv->m_bUnreadBlink)
                            p->drawImage(x, (height - img.height()) / 2, img);
                        x += img.width() + 2;
                    }
                }
            }
            if (!CorePlugin::instance()->value("UseSysColors").toBool())
                p->setPen(CorePlugin::instance()->value("ColorGroup").toUInt());
            QFont f(option.font);
            if (CorePlugin::instance()->value("SmallGroupFont").toBool())
            {
                int size = f.pixelSize();
                if (size > 0)
                    f.setPixelSize(size * 3 / 4);
                else
                {
                    size = f.pointSize();
                    f.setPointSize(size * 3 / 4);
                }
            }
            f.setBold(true);
            p->setFont(f);
            x = drawText(p, x, itemsize, text);
            if (CorePlugin::instance()->value("GroupSeparator").toBool())
                drawSeparator(p, x, itemsize, m_uv->style());
            break;
        }
    case USR_ITEM:
        {
            ContactItem *item = static_cast<ContactItem*>(base);
            QFont f(option.font);
            if (item->style() & CONTACT_ITALIC)
            {
                if (CorePlugin::instance()->value("VisibleStyle").toUInt()  & STYLE_ITALIC)
                    f.setItalic(true);
                if (CorePlugin::instance()->value("VisibleStyle").toUInt()  & STYLE_UNDER)
                    f.setUnderline(true);
                if (CorePlugin::instance()->value("VisibleStyle").toUInt()  & STYLE_STRIKE)
                    f.setStrikeOut(true);
            }
            if (item->style() & CONTACT_UNDERLINE)
            {
                if (CorePlugin::instance()->value("AuthStyle").toUInt()  & STYLE_ITALIC)
                    f.setItalic(true);
                if (CorePlugin::instance()->value("AuthStyle").toUInt()  & STYLE_UNDER)
                    f.setUnderline(true);
                if (CorePlugin::instance()->value("AuthStyle").toUInt()  & STYLE_STRIKE)
                    f.setStrikeOut(true);
            }
            if (item->style() & CONTACT_STRIKEOUT)
            {
                if (CorePlugin::instance()->value("InvisibleStyle").toUInt()  & STYLE_ITALIC)
                    f.setItalic(true);
                if (CorePlugin::instance()->value("InvisibleStyle").toUInt()  & STYLE_UNDER)
                    f.setUnderline(true);
                if (CorePlugin::instance()->value("InvisibleStyle").toUInt()  & STYLE_STRIKE)
                    f.setStrikeOut(true);
            }
            int x = margin;
            QIcon mainIcon = index.data( Qt::DecorationRole ).value<QIcon>();
            if (!mainIcon.isNull())
            {
                QPixmap img = mainIcon.pixmap( 16 );
                x += 2;
                p->drawPixmap(x, ( height - img.height() ) / 2, img);
                x += img.width() + 2;
            }
            if (x < 24)
                x = 24;
            if (!item->isSelected() || !m_uv->hasFocus() || !CorePlugin::instance()->value("UseDblClick").toBool())
            {
                if (!CorePlugin::instance()->value("UseSysColors").toBool())
                {
                    switch (item->status())
                    {
                    case STATUS_ONLINE:
                        p->setPen(CorePlugin::instance()->value("ColorOnline").toUInt());
                        break;
                    case STATUS_FFC:
                        p->setPen(CorePlugin::instance()->value("ColorOnline").toUInt());
                        break;
                    case STATUS_AWAY:
                        p->setPen(CorePlugin::instance()->value("ColorAway").toUInt());
                        break;
                    case STATUS_NA:
                        p->setPen(CorePlugin::instance()->value("ColorNA").toUInt());
                        break;
                    case STATUS_DND:
                        p->setPen(CorePlugin::instance()->value("ColorDND").toUInt());
                        break;
                    default:
                        p->setPen(CorePlugin::instance()->value("ColorOffline").toUInt());
                        break;
                    }
                }
                if (item->status() != STATUS_ONLINE && item->status() != STATUS_FFC)
                    p->setPen(m_uv->palette().color(QPalette::Disabled,QPalette::Text));
            }
            if (item->m_bBlink)
                f.setBold(true);
            else
                f.setBold(false);

            p->setFont(f);
            QString highlight;
            QString text = index.data( Qt::DisplayRole ).toString();
            int pos=0;
            if(!m_uv->m_search.isEmpty())
            {
                pos=text.toUpper().indexOf(m_uv->m_search.toUpper());
                //Search for substring in contact name
                if (pos > -1)
                    highlight=text.mid(pos,m_uv->m_search.length());
            }
            int save_x = x;
            //p->setPen(QColor(0, 0, 0));
            x = drawText(p, x, itemsize, text);
            if (pos > 0)
                save_x = drawText(p, save_x, itemsize, text.left(pos)) - 4;
            x += 2;
            if (!highlight.isEmpty())
            {
                QPen oldPen = p->pen();
                QColor oldBg = p->background().color();
                p->setBackgroundMode(Qt::OpaqueMode);
                if (item == m_uv->m_searchItem)
                    if (item == m_uv->currentItem() && CorePlugin::instance()->value("UseDblClick").toBool())
                    {
                        p->setBackground(cg.color(QPalette::HighlightedText));
                        p->setPen(cg.color(QPalette::Highlight));
                    }
                    else
                    {
                        p->setBackground(cg.color(QPalette::Highlight));
                        p->setPen(cg.color(QPalette::HighlightedText));
                    }
                else
                {
                    p->setBackground(oldPen.color());
                    p->setPen(oldBg);
                }
                drawText(p, save_x, itemsize, highlight);
                p->setPen(oldPen);
                p->setBackground(oldBg);
                p->setBackgroundMode(Qt::TransparentMode);
            }
            unsigned xIcon = width;
            QString icons = index.data( SIM::ExtraIconsRole ).toString();
            while( !icons.isEmpty() ) 
            {
                QString icon = getToken(icons, ',');
                QImage img = Image(icon);
                if (!img.isNull())
                {
                    xIcon -= img.width() + 2;
                    if (xIcon < (unsigned)x)
                        break;
                    p->drawImage(xIcon, (height - img.height()) / 2, img);
                }
            }
            break;
        }
    case DIV_ITEM:
        {
            QString text = index.data( Qt::DisplayRole ).toString();
            QFont f(option.font);
            int size = f.pixelSize();
            if (size <= 0)
            {
                size = f.pointSize();
                f.setPointSize(size * 3 / 4);
            }
            else
                f.setPixelSize(size * 3 / 4);
            p->setFont(f);
            int x = drawText(p, 24 + margin, itemsize, text);
            drawSeparator(p, x, itemsize, m_uv->style());
            break;
        }
    }

    painter->restore();
}
Example #19
0
void StructView::drawAll( QPainter &p )
{
  int h, w, nh, nw;
  int line_busy;
  int li_src_y, li_dst_y;
  int st_y; /* label on elems start y */
  QString src_name;
  h = height(); w = width(); nh = 1 + h / grid_sz; nw = 1 + w / grid_sz;
  if( !sch ) {
    p.setBrush( Qt::red );
    p.drawRect( 0, 0, w, 8 );
    return;
  };

  SettingsData *sett = SETTINGS;
  int s_icons = sett->getDataD( "showIcons", 1 );
  const QFont &strf = sett->getAsFont( QSL("structFont") );
  p.setFont( strf );
  const QFont &smlf = sett->getAsFont( QSL("smallFont" ) );
  QFontMetrics small_fm( smlf );
  em_small = small_fm.width( 'W' );
  ex_small = small_fm.height();
  el_marg = (grid_sz-obj_sz) / 2;
  if( nh >= MODEL_MY ) { nh = MODEL_MY-1; };
  if( nw >= MODEL_MX ) { nh = MODEL_MX-1; };

  auto lockedIcon  = QIcon( ":icons/state-locked.png" );
  auto ignoredIcon = QIcon( ":icons/state-ignored.png" );


  QColor bgCol { ro ? QColor(255,240,240) : Qt::white };
  if( ! hasFocus() ) {
    bgCol = bgCol.darker( 110 );
  }
  p.setBrush( bgCol );
  p.drawRect( 0, 0, w, h );

  // ---------- draw grid
  int showGrid = sett->getDataD( QSL("showGrid"), 1 );
  if( showGrid ) {
    p.setPen( QPen( bgCol.darker(150), 0, Qt::DotLine ) ); // TODO: config
    for( int i=0; i<nw; i++ ) {
      int x = lm + i*grid_sz;
      p.drawLine( x, tm, x, h );
    }
    for( int i=0; i<nh; i++ ) {
      int y = tm + i*grid_sz;
      p.drawLine( lm, y, w, y );
    }
  };

  p.setPen( Qt::black );
  // --------- draw elems ---------------------
  int cr_diff = el_marg/3;
  QPoint p_crp {  cr_diff, cr_diff }; // difs for cross and arrow
  QPoint p_crm { -cr_diff, cr_diff };

  ElemInfo ei, sei;
  for( auto ob : sch->TCHILD(TMiso*) ) {
    if( ! fill_elmInfo( ob, ei ) ) {
      qWarning() << "Fail fo fill info for " << ob->getFullName() << WHE;
      continue;
    }
    line_busy = 0;
    if( ei.vis_x < 0 || ei.vis_y < 0  ) {
      continue;
    }
    p.setPen( Qt::black );

    // --------------------- draw element icon or frame
    if( ei.noIcon || !s_icons ) {
      p.setPen( QPen(Qt::black,2) );  p.setBrush( Qt::NoBrush );
      p.drawRect( ei.xs, ei.ys, obj_sz, obj_sz );
    } else {
      QIcon el_ico = ob->getIcon();
      el_ico.paint( &p, ei.xs, ei.ys, obj_sz, obj_sz );
    };
    p.setPen( Qt::black );  p.setBrush( Qt::red );

    // special marks: TODO: icons
    if( ei.locked ) {
      // p.drawRect( ei.xs + 4, ei.ys + 8, 20, 8 );
      lockedIcon.paint( &p, ei.xs, ei.ys, obj_sz, obj_sz );
    }
    if( ei.ignored ) {
      ignoredIcon.paint( &p, ei.xs, ei.ys, obj_sz, obj_sz );
    }
    if( ei.onlyFirst ) {
      p.drawRect( ei.xs + 4, ei.ys + 14, 6, 6 );
    }
    if( ei.onlyLast ) {
      p.drawRect( ei.xs + 20, ei.ys +14, 6, 6 );
    }


    // order mark
    int showOrd = sett->getDataD( QSL("showOrd"), 0 );
    if( showOrd ) {
      if( s_icons && ! ei.noIcon )  {
        p.setPen( Qt::NoPen ); p.setBrush( QColor(240,240,255) );
        p.drawRect( ei.xs, ei.ys, obj_sz-1, ex_small );
      };
      p.setPen( Qt::black );
      p.drawText( ei.xs + 2, ei.ys + ex_small, QSN( ei.ord ) );
      line_busy++;
    };
    // --------------------- draw element name
    int showNames = sett->getDataD( QSL("showNames"), 1 );
    if( showNames ) {
      st_y = ei.ys + line_busy*ex_small;
      if( s_icons && ! ei.noIcon )  {
        p.setPen( Qt::NoPen ); p.setBrush( QColor(255,255,225) );
        p.drawRect( ei.xs, st_y, obj_sz-1, ex_small );
      };
      p.setPen( Qt::black );
      p.drawText( ei.xs + 2, st_y+ex_small, ei.name );
      line_busy++;
    };

    int mod = ob->getModified(); // ---------- modification marks
    if( mod ) {
      p.setPen( Qt::NoPen );  p.setBrush( QColor( 255, 150, 150, 128 ) );
      p.drawRect( ei.xs, ei.ys+1, obj_sz-3, obj_sz/2 );
    }

    // TODO: vector icon here
    p.setBrush( Qt::NoBrush ); p.setPen( QPen(Qt::black,1) );
    st_y = ei.ys + line_busy*ex_small;


    int showLinks = sett->getDataD( QSL("showLinks"), 1 );
    if( !showLinks || ei.ignored ) {
      continue;
    }

    //  input marks
    int in_sep_sz = obj_sz/(ei.n_inp+1);
    p.setFont( smlf );
    p.setBrush( Qt::NoBrush );

    // ordinary inputs
    int i_in=0;
    for( const InputSimple *in : ob->TCHILD(const InputSimple*) ) {
      ++i_in;
      if( ! in ) {
        continue;
      }
      int lt = in->getDataD( "linkType", LinkBad );
      const TDataSet* sobj = in->getSourceObj();
      li_dst_y = ei.ys + i_in*in_sep_sz;
      int line_width = in->getDataD( "line_w", 1 );
      int x_shift    = in->getDataD( "x_shift", 0 );
      int y_shift    = in->getDataD( "y_shift", 0 );
      QColor lco = Qt::black;
      in->getData( "line_color", lco );
      p.setPen( QPen( lco, line_width ) );

      if( lt == LinkNone ) {
        p.drawEllipse( QPoint(ei.li_dst_x, li_dst_y), el_marg/3, el_marg/3 );
        continue;
      }
      int x_vert = ei.pre_dst_x + x_shift * ei.flip_factor;
      // arrow
      // p.drawLine( pre_dst_x, li_dst_y,   li_dst_x, li_dst_y  );
      p.drawLine( ei.li_dst_x, li_dst_y, x_vert, li_dst_y );
      p.drawLine( ei.li_dst_x +  3*ei.flip_factor, li_dst_y-2, ei.li_dst_x, li_dst_y  );
      p.drawLine( ei.li_dst_x +  3*ei.flip_factor, li_dst_y+2, ei.li_dst_x, li_dst_y  );

      QString lbl = in->getDataD( "label", QString() );
      if( ! lbl.isEmpty() ) {
        p.drawText( x_vert-2*ei.flip_factor, li_dst_y-2, lbl );
      }

      if( lt == LinkBad ) {
        p.setPen( QPen( Qt::red, 2 ) );
        p.drawLine( x_vert-el_marg/3, li_dst_y-el_marg/3,
                    x_vert+el_marg/3, li_dst_y+el_marg/3 );
        p.drawLine( x_vert-el_marg/3, li_dst_y+el_marg/3,
                    x_vert+el_marg/3, li_dst_y-el_marg/3 );
        continue;
      }

      if( lt == LinkSpec ) {
        p.setPen( QPen( Qt::magenta, 2 ) );
        p.drawRect( x_vert-el_marg/4, li_dst_y-el_marg/4, el_marg/2, el_marg/2 );
        continue;
      }

      // here must be ordinary sources -> large mark if not so
      const TMiso *so_obj = nullptr;
      if( !sobj || ( (so_obj = qobject_cast<const TMiso*>(sobj)) == nullptr ) ) {
        p.setPen( QPen( Qt::red, 4 ) );
        p.drawEllipse( QPoint(x_vert, li_dst_y), el_marg, el_marg );
        continue;
      }

      // get info about source and calc coords
      fill_elmInfo( so_obj, sei );
      QString so = in->getDataD( "source", QString() );

      if( ei.vis_y != sei.vis_y ) {
        li_src_y = sei.yc - y_shift;
      } else {
        li_src_y = li_dst_y - y_shift; // special case: one line
      }

      if( so.contains(".") ) { // complex - not 'out0' source
        QChar qshc = (so.right(1))[0];
        char shc = qshc.toLatin1();
        li_src_y += 2 + ( shc  & 0x07 );
        p.drawLine( sei.li_src_x + el_marg*sei.flip_factor/2, li_src_y,
                    sei.li_src_x + el_marg*sei.flip_factor/2, li_src_y+3 );
      }

      p.drawLine( sei.li_src_x, li_src_y,
                  sei.li_src_x + el_marg*sei.flip_factor, li_src_y );

      int only_lbl = in->getDataD( "onlyLabel", 0 );
      if( only_lbl ) {
        if( ! lbl.isEmpty() ) {
          p.drawText( sei.li_src_x+(3+el_marg)*sei.flip_factor, li_src_y-2, lbl );
        }
        continue;
      }

      p.drawLine( x_vert, li_dst_y, x_vert, li_src_y ); // vertical part
      p.drawLine( x_vert, li_src_y, sei.li_src_x, li_src_y); // horiz. from src

    } // end of simple input loop


    // ----------- parametric inputs
    i_in=0;
    in_sep_sz = obj_sz/(ei.n_pinp+1);
    for( const auto ips : ob->TCHILD(const ParamDouble*) ) {
      if( !ips ) { continue; }
      int lt = ips->getLinkType();

      if( lt == LinkNone ) { continue; }

      int line_width = ips->getDataD( "line_w", 2 );
      int x_shift = ips->getDataD( "x_shift", 0 );
      int y_shift = ips->getDataD( "y_shift", 0 );
      QColor lco = Qt::black;
      ips->getData( "line_color", lco );
      p.setPen( QPen( lco, line_width ) );

      int li_pdst_x = ei.xs + (1+i_in) * in_sep_sz;
      QPoint p_bott { li_pdst_x, ei.li_pdst_y+el_marg };
      QPoint p_dst  { li_pdst_x, ei.li_pdst_y };

      // arrow
      p.drawLine( p_bott, p_dst );
      p.drawLine( p_dst+p_crp, p_dst );
      p.drawLine( p_dst+p_crm, p_dst );

      if( lt == LinkBad ) {
        p.setPen( QPen( Qt::red, 2 ) );
        p.drawLine( p_bott+p_crp, p_bott-p_crp );
        p.drawLine( p_bott+p_crm, p_bott-p_crm );
        continue;
      }

      if( lt == LinkSpec ) {
        p.setPen( QPen( Qt::magenta, 2 ) );
        p.drawRect( QRect( p_bott, QSize(el_marg/2, el_marg/2) ) );
        continue;
      }

      if( lt != LinkElm ) { // later must be ordinary link
        qWarning() << "Unknown link type " << lt << " for " << ips->getFullName() << WHE;
        continue;
      }

      const TDataSet* sobj = ips->getSourceObj();
      const TMiso *so_obj = nullptr;
      if( !sobj || ( (so_obj = qobject_cast<const TMiso*>(sobj)) == nullptr ) ) {
        p.setPen( QPen( Qt::red, 4 ) );
        p.drawEllipse( p_bott, el_marg, el_marg );
        continue;
      }

      fill_elmInfo( so_obj, sei );

      li_src_y = sei.yc - y_shift;

      // TODO: label
      int only_lbl = ips->getDataD( "onlyLabel", 0 );

      int x_vert = sei.li_src_x - ( x_shift + el_marg ) * sei.flip_factor;

      p.drawLine( sei.li_src_x, li_src_y, x_vert, li_src_y ); // from src
      if( ! only_lbl ) {
        p.drawLine( x_vert, ei.li_pdst_y+el_marg,  x_vert, li_src_y ); // vert line
        p.drawLine( p_bott, QPoint( x_vert, ei.li_pdst_y+el_marg ) );  // to dst.bottom
      }

      ++i_in;
    } // end of param input loop

  }; // end loop on elems
void OscilloscopeView::paintEvent( QPaintEvent *e)
{
	QRect r = e->rect();
	
	if(b_needRedraw)
	{
		updateOutputHeight();
		const double pixelsPerSecond = Oscilloscope::self()->pixelsPerSecond();
		
        if (!m_pixmap) {
            qWarning() << Q_FUNC_INFO << " unexpected null m_pixmap in " << this;
            return;
        }

		QPainter p;
		m_pixmap->fill( paletteBackgroundColor());
		const bool startSuccess = p.begin(m_pixmap);
        if ((!startSuccess) || (!p.isActive())) {
            qWarning() << Q_FUNC_INFO << " painter is not active";
        }

		p.setClipRegion(e->region());
		
		//BEGIN Draw vertical marker lines
		const double divisions = 5.0;
		const double min_sep = 10.0;
		
		double spacing = pixelsPerSecond/(std::pow( divisions, std::floor(std::log(pixelsPerSecond/min_sep)/std::log(divisions))));
		
		// Pixels offset is the number of pixels that the view is scrolled along
		const int64_t pixelsOffset = int64_t(Oscilloscope::self()->scrollTime()*pixelsPerSecond/LOGIC_UPDATE_RATE);
		double linesOffset = - lld_modulus( pixelsOffset, spacing);
		
		int blackness = 256 - int(184.0 * spacing / (min_sep*divisions*divisions));
		p.setPen( QColor( blackness, blackness, blackness));
		
		for( double i = linesOffset; i <= frameRect().width(); i += spacing)
			p.drawLine( int(i), 1, int(i), frameRect().height()-2);
		
		
		
		spacing *= divisions;
		linesOffset = - lld_modulus( pixelsOffset, spacing);
		
		blackness = 256 - int(184.0 * spacing / (min_sep*divisions*divisions));
		p.setPen( QColor( blackness, blackness, blackness));
		
		for( double i = linesOffset; i <= frameRect().width(); i += spacing)
			p.drawLine( int(i), 1, int(i), frameRect().height()-2);
		
		
		
		spacing *= divisions;
		linesOffset = - lld_modulus( pixelsOffset, spacing);
		
		blackness = 256 - int(184.0);
		p.setPen( QColor( blackness, blackness, blackness));
		
		for( double i = linesOffset; i <= frameRect().width(); i += spacing)
			p.drawLine( int(i), 1, int(i), frameRect().height()-2);
		//END Draw vertical marker lines
		
		drawLogicData(p);
		drawFloatingData(p);
		
		p.setPen(Qt::black);
		p.drawRect( frameRect());
		
		b_needRedraw = false;
	}
	
	bitBlt( this, r.x(), r.y(), m_pixmap, r.x(), r.y(), r.width(), r.height());
}
Example #21
0
// Dessine l'isoligne dans un QPainter
void drawCube(QPainter &painter, size_t i, size_t j, const std::vector< std::vector< float >* >* interpoleShepard, const std::vector< std::vector< short >* >* square, float isoLine) {
    painter.setPen(Qt::red);
    //painter.drawRect(i*RESO, j*RESO, RESO, RESO);

    int n = square->at(i)->at(j);
    bool b = ((interpoleShepard->at(i)->at(j) + interpoleShepard->at(i)->at(j+1) +
              interpoleShepard->at(i+1)->at(j+1) + interpoleShepard->at(i+1)->at(j)) / 4.0) > isoLine;

    // Calcul des coefficients
    float is1 = interpoleShepard->at(i)->at(j);
    float is2 = interpoleShepard->at(i)->at(j+1);
    float is3 = interpoleShepard->at(i+1)->at(j+1);
    float is4 = interpoleShepard->at(i+1)->at(j);
    float t1 = (isoLine - is1) / (is2 - is1);
    float t2 = (isoLine - is2) / (is3 - is2);
    float t3 = (isoLine - is4) / (is3 - is4);
    float t4 = (isoLine - is1) / (is4 - is1);

    QPoint p1 = QPoint(-1, -1);
    QPoint p2 = QPoint(-1, -1);
    QPoint pt1 = QPoint((j+t1)*RESO, i*RESO);
    QPoint pt2 = QPoint((j+1)*RESO, (i+t2)*RESO);
    QPoint pt3 = QPoint((j+t3)*RESO, (i+1)*RESO);
    QPoint pt4 = QPoint(j*RESO, (i+t4)*RESO);

    if (n == 0 || n == 15) {

    }

    if (n == 1 || n == 14) {
        p1 = pt1;
        p2 = pt4;
    } else if (n == 2 || n == 13) {
        p1 = pt1;
        p2 = pt2;
    } else if (n == 4 || n == 11) {
        p1 = pt2;
        p2 = pt3;
    } else if (n == 7 || n == 8) {
        p1 = pt3;
        p2 = pt4;
    }

    if (n == 3 || n == 12) {
        p1 = pt2;
        p2 = pt4;
    } else if (n == 5) {
        if (b) {
            p1 = pt1;
            p2 = pt2;
            painter.setPen(Qt::yellow);
            painter.drawLine(pt3, pt4);
        } else {
            p1 = pt1;
            p2 = pt4;
            painter.setPen(Qt::yellow);
            painter.drawLine(pt2, pt3);
        }
    } else if (n == 6 || n == 9) {
        p1 = pt1;
        p2 = pt3;
    } else if (n == 10) {
        if (b) {
            p1 = pt1;
            p2 = pt4;
            painter.setPen(Qt::yellow);
            painter.drawLine(pt2, pt3);
        } else {
            p1 = pt1;
            p2 = pt2;
            painter.setPen(Qt::yellow);
            painter.drawLine(pt3, pt4);
        }
    }

    painter.setPen(Qt::red);
    painter.drawLine(p1, p2);
}
void OscilloscopeView::drawLogicData( QPainter & p)
{
	const double pixelsPerSecond = Oscilloscope::self()->pixelsPerSecond();
	
	const LogicProbeDataMap::iterator end = Oscilloscope::self()->m_logicProbeDataMap.end();
	for( LogicProbeDataMap::iterator it = Oscilloscope::self()->m_logicProbeDataMap.begin(); it != end; ++it)
	{
		// When searching for the next logic value to display, we look along
		// until there is a recorded point which is at least one pixel along
		// If we are zoomed out far, there might be thousands of data points
		// between each pixel. It is time consuming searching for the next point
		// to display one at a time, so we record the average number of data points
		// between pixels ( = deltaAt / totalDeltaAt)
		int64_t deltaAt = 1;
		int totalDeltaAt = 1;
		
		LogicProbeData * probe = it.data();

		vector<LogicDataPoint> *data = probe->m_data;
		if(!data->size()) continue;
		
		const int midHeight = Oscilloscope::self()->probePositioner->probePosition(probe);
		const int64_t timeOffset = Oscilloscope::self()->scrollTime();
		
		// Draw the horizontal line indicating the midpoint of our output
		p.setPen( QColor( 228, 228, 228));
		p.drawLine( 0, midHeight, width(), midHeight);
		
		// Set the pen colour according to the colour the user has selected for the probe
		p.setPen( probe->color());
		
		// The smallest time step that will display in our oscilloscope
		const int minTimeStep = int(LOGIC_UPDATE_RATE/pixelsPerSecond);
		
		int64_t at = probe->findPos(timeOffset);
		const int64_t maxAt = probe->m_data->size();
		int64_t prevTime = (*data)[at].time;
		int prevX = (at > 0) ? 0 : int((prevTime - timeOffset)*(pixelsPerSecond/LOGIC_UPDATE_RATE));
		bool prevHigh = (*data)[at].value;
		int prevY = midHeight + int(prevHigh ? -m_halfOutputHeight : +m_halfOutputHeight);

		while ( at < maxAt) {
			// Search for the next pos which will show up at our zoom level
			int64_t previousAt = at;
			int64_t dAt = deltaAt / totalDeltaAt;
			
			while ( (dAt > 1) && (at < maxAt) && ( (int64_t((*data)[at].time) - prevTime) != minTimeStep))
			{
				// Search forwards until we overshoot
				while ( at < maxAt && ( int64_t((*data)[at].time) - prevTime) < minTimeStep)
					at += dAt;
				dAt /= 2;
				
				// Search backwards until we undershoot
				while ( (at < maxAt) && ( int64_t((*data)[at].time) - prevTime) > minTimeStep)
				{
					at -= dAt;
					if( at < 0)
						at = 0;
				}
				dAt /= 2;
			}
			
			// Possibly increment the value of at found by one (or more if this is the first go)
			while ( (previousAt == at) || ((at < maxAt) && ( int64_t((*data)[at].time) - prevTime) < minTimeStep))
				at++;

			if( at >= maxAt) break;

			// Update the average values
			deltaAt += at - previousAt;
			totalDeltaAt++;
			
			bool nextHigh = (*data)[at].value;
			if( nextHigh == prevHigh) continue;

			int64_t nextTime = (*data)[at].time;
			int nextX = int((nextTime - timeOffset)*(pixelsPerSecond/LOGIC_UPDATE_RATE));
			int nextY = midHeight + int(nextHigh ? -m_halfOutputHeight : +m_halfOutputHeight);
			
			p.drawLine( prevX, prevY, nextX, prevY);
			p.drawLine( nextX, prevY, nextX, nextY);

			prevHigh = nextHigh;
			prevTime = nextTime;
			prevX = nextX;
			prevY = nextY;

			if( nextX > width()) break;
		};
		
		// If we could not draw right to the end; it is because we exceeded
		// maxAt
		if( prevX < width())
			p.drawLine( prevX, prevY, width(), prevY);
	}
}
Example #23
0
QFileInfo saveWidgetAsImage(QObject* wid, const QRect& r, const QString& dialogTitle, const QString& defaultPath, const AppSettings & appSetting)
{
    QFileInfo fileInfo;
    
    QGraphicsScene* scene = 0;
    QWidget* widget = dynamic_cast<QWidget*>(wid);
    GraphView* mGraph = dynamic_cast<GraphView*>(wid);
    
    if(!mGraph && !widget)
    {
        scene = dynamic_cast<QGraphicsScene*>(wid);
        if(!scene)
            return fileInfo;
    }
    
    QString filter = QObject::tr("Image (*.png);;Photo (*.jpg);; Windows Bitmap (*.bmp);;Scalable Vector Graphics (*.svg)");
    QString fileName = QFileDialog::getSaveFileName(qApp->activeWindow(),
                                                    dialogTitle,
                                                    defaultPath,
                                                    filter);
    if(!fileName.isEmpty())
    {
        fileInfo = QFileInfo(fileName);
        QString fileExtension = fileInfo.suffix();
        
        //QString fileExtension = fileName.(".svg");
       // bool asSvg = fileName.endsWith(".svg");
       // if(asSvg)
        //QFontMetrics fm((scene ? qApp->font() : widget->font()));
        
        float heightText = r.height()/50; //fm.height() + 30;
        /*if (heightText<10) {
            heightText = 10;
        }*/
        if(fileExtension == "svg")
        {
            if(mGraph)
            {
                mGraph->saveAsSVG(fileName, "Title", "Description",true);
            }
            else if(scene)
            {
                QSvgGenerator svgGen;
                svgGen.setFileName(fileName);
                svgGen.setSize(r.size());
                svgGen.setViewBox(QRect(0, 0, r.width(), r.height()));
                svgGen.setDescription(QObject::tr("SVG scene drawing "));
                //qDebug()<<"export scene as SVG";
                
                QPainter p;
                p.begin(&svgGen);
                scene->render(&p, r, r);
                p.end();
            }
            else if(widget)
            {
                saveWidgetAsSVG(widget, r, fileName);
            }
        }
        else
        { // save PNG
            
            //int versionHeight = 20;
            //qreal pr = 1;//qApp->devicePixelRatio();
           /* qreal prh=  32000. / ( r.height() + versionHeight) ; // QImage axes are limited to 32767x32767 pixels
           
            qreal prw=  32000. / r.width() ;                  qreal pr = (prh<prw)? prh : prw;
            if (pr>4) {
                pr=4;
            }
            */
            
            // -------------------------------
            //  Get preferences
            // -------------------------------
            short pr = appSetting.mPixelRatio;
            short dpm = appSetting.mDpm;
            short quality = appSetting.mImageQuality;
            
            // -------------------------------
            //  Create the image
            // -------------------------------
            QImage image(r.width() * pr, (r.height() + heightText) * pr , QImage::Format_ARGB32_Premultiplied);
            if(image.isNull()){
                qDebug() << "Cannot export null image!";
                return fileInfo;
            }
            
            // -------------------------------
            //  Set image properties
            // -------------------------------
            image.setDotsPerMeterX(dpm * 11811.024 / 300.);
            image.setDotsPerMeterY(dpm * 11811.024 / 300.);
            image.setDevicePixelRatio(pr);
            
            // -------------------------------
            //  Fill background
            // -------------------------------
            if (fileExtension == "jpg") {
                image.fill(Qt::white);
            }
            else {
                image.fill(Qt::transparent);
            }
            
            // -------------------------------
            //  Create painter
            // -------------------------------
            QPainter p;
            p.begin(&image);
            p.setRenderHint(QPainter::Antialiasing);
            
            // -------------------------------
            //  If widget, draw with or without axis
            // -------------------------------
            if(widget){
                //p.setFont(widget->font());
                widget->render(&p, QPoint(0, 0), QRegion(r.x(), r.y(), r.width(), r.height()));
            }
            
            // -------------------------------
            //  If scene...
            // -------------------------------
            else if(scene){
                QRectF srcRect = r;
                srcRect.setX(r.x());
                srcRect.setY(r.y());
                srcRect.setWidth(r.width() * pr);
                srcRect.setHeight(r.height() * pr);
                
                QRectF tgtRect = image.rect();
                tgtRect.adjust(0, 0, 0, -heightText * pr);
                
                scene->render(&p, tgtRect, srcRect);
            }
            
            // -------------------------------
            //  Write application and version
            // -------------------------------
            QFont ft = scene ? qApp->font() : widget->font();
            ft.setPixelSize(heightText);
            
            p.setFont(ft);
            p.setPen(Qt::black);
            
            p.drawText(0, r.height(), r.width(), heightText,
                       Qt::AlignCenter,
                       qApp->applicationName() + " " + qApp->applicationVersion());
            p.end();
            
            // -------------------------------
            //  Save file
            // -------------------------------
            image.save(fileName, fileExtension.toUtf8(), quality);
            
            //image.save(fileName, formatExt);
            /*QImageWriter writer;
             writer.setFormat("jpg");
             writer.setQuality(100);
             writer.setFileName(fileName+"_jpg");
             writer.write(image);*/
        }
    }

    
    return fileInfo;
}
Example #24
0
void Font::drawComplexText(GraphicsContext* ctx, const TextRun& run, const FloatPoint& point, int from, int to) const
{
    if (to < 0)
        to = run.length();

    QPainter *p = ctx->platformContext();

    if (ctx->textDrawingMode() & cTextFill) {
        if (ctx->fillGradient()) {
            QBrush brush(*ctx->fillGradient()->platformGradient());
            brush.setTransform(ctx->fillGradient()->gradientSpaceTransform());
            p->setPen(QPen(brush, 0));
        } else if (ctx->fillPattern()) {
            TransformationMatrix affine;
            p->setPen(QPen(QBrush(ctx->fillPattern()->createPlatformPattern(affine)), 0));
        } else
            p->setPen(QColor(ctx->fillColor()));
    }

    if (ctx->textDrawingMode() & cTextStroke) {
        if (ctx->strokeGradient()) {
            QBrush brush(*ctx->strokeGradient()->platformGradient());
            brush.setTransform(ctx->strokeGradient()->gradientSpaceTransform());
            p->setPen(QPen(brush, ctx->strokeThickness()));
        } else if (ctx->strokePattern()) {
            TransformationMatrix affine;
            p->setPen(QPen(QBrush(ctx->strokePattern()->createPlatformPattern(affine)), ctx->strokeThickness()));
        } else
            p->setPen(QPen(QColor(ctx->strokeColor()), ctx->strokeThickness()));
    }

    const QString string = fixSpacing(qstring(run));

    // text shadow
    IntSize shadowSize;
    int shadowBlur;
    Color shadowColor;
    bool hasShadow = ctx->textDrawingMode() == cTextFill && ctx->getShadow(shadowSize, shadowBlur, shadowColor);

    if (from > 0 || to < run.length()) {
        QTextLayout layout(string, font());
        QTextLine line = setupLayout(&layout, run);
        float x1 = line.cursorToX(from);
        float x2 = line.cursorToX(to);
        if (x2 < x1)
            qSwap(x1, x2);

        QFontMetrics fm(font());
        int ascent = fm.ascent();
        QRectF clip(point.x() + x1, point.y() - ascent, x2 - x1, fm.height());

        if (hasShadow) {
            // TODO: when blur support is added, the clip will need to account
            // for the blur radius
            qreal dx1 = 0, dx2 = 0, dy1 = 0, dy2 = 0;
            if (shadowSize.width() > 0)
                dx2 = shadowSize.width();
            else
                dx1 = -shadowSize.width();
            if (shadowSize.height() > 0)
                dy2 = shadowSize.height();
            else
                dy1 = -shadowSize.height();
            // expand the clip rect to include the text shadow as well
            clip.adjust(dx1, dx2, dy1, dy2);
        }
        p->save();
        p->setClipRect(clip.toRect());
        QPointF pt(point.x(), point.y() - ascent);
        if (hasShadow) {
            p->save();
            p->setPen(QColor(shadowColor));
            p->translate(shadowSize.width(), shadowSize.height());
            line.draw(p, pt);
            p->restore();
        }
        line.draw(p, pt);
        p->restore();
        return;
    }

    p->setFont(font());

    QPointF pt(point.x(), point.y());
    int flags = run.rtl() ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight;
    if (hasShadow) {
        // TODO: text shadow blur support
        p->save();
        p->setPen(QColor(shadowColor));
        p->translate(shadowSize.width(), shadowSize.height());
        p->drawText(pt, string, flags, run.padding());
        p->restore();
    }
    if (ctx->textDrawingMode() & cTextStroke) {
        QPainterPath path;
        path.addText(pt, font(), string);
        p->strokePath(path, p->pen());
    }
    if (ctx->textDrawingMode() & cTextFill)
        p->drawText(pt, string, flags, run.padding());
}
Example #25
0
void QgsTextDiagram::renderDiagram( const QgsFeature& feature, QgsRenderContext& c, const QgsDiagramSettings& s, const QPointF& position )
{
  Q_UNUSED( feature );

  QPainter* p = c.painter();
  if ( !p )
  {
    return;
  }

  double scaleDenominator = c.rendererScale();
  if (( s.minScaleDenominator != -1 && scaleDenominator < s.minScaleDenominator )
      || ( s.maxScaleDenominator != -1 && scaleDenominator > s.maxScaleDenominator ) )
  {
    return;
  }

  //convert from mm / map units to painter units
  QSizeF spu = sizePainterUnits( s.size, s, c );
  double w = spu.width();
  double h = spu.height();

  double baseX = position.x();
  double baseY = position.y() - h;

  QList<QPointF> textPositions; //midpoints for text placement
  int nCategories = s.categoryAttributes.size();
  for ( int i = 0; i < nCategories; ++i )
  {
    if ( mOrientation == Horizontal )
    {
      textPositions.push_back( QPointF( baseX + ( w / nCategories ) * i + w / nCategories / 2.0, baseY + h / 2.0 ) );
    }
    else //vertical
    {
      textPositions.push_back( QPointF( baseX + w / 2.0, baseY + h / nCategories * i + w / nCategories / 2.0 ) );
    }
  }

  mPen.setColor( s.penColor );
  setPenWidth( mPen, s, c );
  p->setPen( mPen );
  mBrush.setColor( s.backgroundColor );
  p->setBrush( mBrush );

  //draw shapes and separator lines first
  if ( mShape == Circle )
  {
    p->drawEllipse( baseX, baseY, w, h );

    //draw separator lines
    QList<QPointF> intersect; //intersections between shape and separation lines
    QPointF center( baseX + w / 2.0, baseY + h / 2.0 );
    double r1 = w / 2.0; double r2 = h / 2.0;

    for ( int i = 1; i < nCategories; ++i )
    {
      if ( mOrientation == Horizontal )
      {
        lineEllipseIntersection( QPointF( baseX + w / nCategories * i, baseY ), QPointF( baseX + w / nCategories * i, baseY + h ), center, r1, r2, intersect );
      }
      else //vertical
      {
        lineEllipseIntersection( QPointF( baseX, baseY + h / nCategories * i ), QPointF( baseX + w, baseY + h / nCategories * i ), center, r1, r2, intersect );
      }
      if ( intersect.size() > 1 )
      {
        p->drawLine( intersect.at( 0 ), intersect.at( 1 ) );
      }
    }
  }
  else if ( mShape == Rectangle )
  {
    p->drawRect( QRectF( baseX, baseY, w, h ) );
    for ( int i = 1; i < nCategories; ++i )
    {
      if ( mOrientation == Horizontal )
      {
        p->drawLine( QPointF( baseX + w / nCategories * i, baseY ), QPointF( baseX + w / nCategories * i, baseY + h ) );
      }
      else
      {
        p->drawLine( QPointF( baseX, baseY + h / nCategories * i ), QPointF( baseX + w, baseY + h / nCategories * i ) );
      }
    }
  }
  else //triangle
  {
    QPolygonF triangle;
    triangle << QPointF( baseX, baseY + h ) << QPointF( baseX + w, baseY + h ) << QPointF( baseX + w / 2.0, baseY );
    p->drawPolygon( triangle );

    QLineF triangleEdgeLeft( baseX + w / 2.0, baseY, baseX, baseY + h );
    QLineF triangleEdgeRight( baseX + w, baseY + h, baseX + w / 2.0, baseY );
    QPointF intersectionPoint1, intersectionPoint2;

    for ( int i = 1; i < nCategories; ++i )
    {
      if ( mOrientation == Horizontal )
      {
        QLineF verticalLine( baseX + w / nCategories * i, baseY + h, baseX + w / nCategories * i, baseY );
        if ( baseX + w / nCategories * i < baseX + w / 2.0 )
        {
          verticalLine.intersect( triangleEdgeLeft, &intersectionPoint1 );
        }
        else
        {
          verticalLine.intersect( triangleEdgeRight, &intersectionPoint1 );
        }
        p->drawLine( QPointF( baseX + w / nCategories * i, baseY + h ), intersectionPoint1 );
      }
      else //vertical
      {
        QLineF horizontalLine( baseX, baseY + h / nCategories * i, baseX + w, baseY + h / nCategories * i );
        horizontalLine.intersect( triangleEdgeLeft, &intersectionPoint1 );
        horizontalLine.intersect( triangleEdgeRight, &intersectionPoint2 );
        p->drawLine( intersectionPoint1, intersectionPoint2 );
      }
    }
  }

  //draw text
  QFont sFont = scaledFont( s, c );
  QFontMetricsF fontMetrics( sFont );
  p->setFont( sFont );

  for ( int i = 0; i < textPositions.size(); ++i )
  {
    QgsExpression* expression = getExpression( s.categoryAttributes.at( i ), feature.fields() );
    QString val = expression->evaluate( feature ).toString();

    //find out dimesions
    double textWidth = fontMetrics.width( val );
    double textHeight = fontMetrics.height();

    mPen.setColor( s.categoryColors.at( i ) );
    p->setPen( mPen );
    QPointF position = textPositions.at( i );

    // Calculate vertical placement
    double xOffset = 0;

    switch ( s.labelPlacementMethod )
    {
      case QgsDiagramSettings::Height:
        xOffset = textHeight / 2.0;
        break;

      case QgsDiagramSettings::XHeight:
        xOffset = fontMetrics.xHeight();
        break;
    }
    p->drawText( QPointF( position.x() - textWidth / 2.0, position.y() + xOffset ), val );
  }
}
Example #26
0
void GeometryPainter::drawPolygon(QPainter& pt, const OGRPolygon* polygon, const QMatrix& m)
{
  QPen pen = pt.pen();
  QBrush brush = pt.brush();

  if (polygon->getNumInteriorRings() > 0)
  {
    QPainter* lpt = NULL;
    QImage* image = new QImage(pt.window().size(), QImage::Format_ARGB32);
    if (image->isNull() == true)
    {
      delete image;
      throw Exception("Internal Error: GeometryPainter::drawPolygon "
                      "Error allocating image.");
    }
    image->fill(qRgba(0, 0, 0, 0));
    lpt = new QPainter(image);
    lpt->setMatrix(pt.matrix());
    lpt->setPen(pen);
    lpt->setBrush(brush);

    const OGRLinearRing* ring = polygon->getExteriorRing();
    QPolygonF qp;
    _convertRingToQPolygon(ring, qp, m);

    lpt->setPen(Qt::NoPen);
    lpt->setBrush(brush);
    lpt->drawPolygon(qp, Qt::WindingFill);

    lpt->setPen(pen);
    lpt->setBrush(Qt::NoBrush);
    lpt->drawPolygon(qp);
    for (int i = 0; i < polygon->getNumInteriorRings(); i++)
    {
      ring = polygon->getInteriorRing(i);

      // draw the appropriate border around the section we erased.
      _convertRingToQPolygon(ring, qp, m);

      // clear out the hole
      lpt->setPen(Qt::NoPen);
      lpt->setBrush(QColor(0, 0, 0, 0));
      lpt->setCompositionMode(QPainter::CompositionMode_Clear);
      lpt->drawPolygon(qp, Qt::WindingFill);

      lpt->setPen(pen);
      lpt->setBrush(Qt::NoBrush);
      lpt->setCompositionMode(QPainter::CompositionMode_SourceOver);
      lpt->drawPolygon(qp, Qt::WindingFill);
    }

    lpt->end();

    QMatrix m = pt.matrix();
    pt.resetMatrix();
    pt.drawImage(pt.window(), *image);
    pt.setMatrix(m);

    delete lpt;
    delete image;
  }
  else
  {
    const OGRLinearRing* ring = polygon->getExteriorRing();
    QPolygonF qp;
    _convertRingToQPolygon(ring, qp, m);

    pt.setPen(Qt::NoPen);
    pt.setBrush(brush);
    pt.drawPolygon(qp, Qt::WindingFill);

    pt.setPen(pen);
    pt.setBrush(Qt::NoBrush);
    pt.drawPolygon(qp);
  }
}
Example #27
0
void QtGrid::draw16FieldSubGrid( QPainter &painter )
{
    draw16FieldGrid( painter );
    painter.setPen( QPen( subgrid_color, 1 ) );
}
void KisFreeTransformStrategy::paint(QPainter &gc)
{
    gc.save();

    gc.setOpacity(m_d->transaction.basePreviewOpacity());
    gc.setTransform(m_d->paintingTransform, true);
    gc.drawImage(m_d->paintingOffset, originalImage());

    gc.restore();

    // Draw Handles

    qreal d = 1;
    QRectF handleRect =
        KisTransformUtils::handleRect(KisTransformUtils::handleVisualRadius,
                                      m_d->handlesTransform,
                                      m_d->transaction.originalRect(),
                                      &d);

    qreal r = 1;
    QRectF rotationCenterRect =
        KisTransformUtils::handleRect(KisTransformUtils::rotationHandleVisualRadius,
                                      m_d->handlesTransform,
                                      m_d->transaction.originalRect(),
                                      &r);

    QPainterPath handles;

    handles.moveTo(m_d->transaction.originalTopLeft());
    handles.lineTo(m_d->transaction.originalTopRight());
    handles.lineTo(m_d->transaction.originalBottomRight());
    handles.lineTo(m_d->transaction.originalBottomLeft());
    handles.lineTo(m_d->transaction.originalTopLeft());

    handles.addRect(handleRect.translated(m_d->transaction.originalTopLeft()));
    handles.addRect(handleRect.translated(m_d->transaction.originalTopRight()));
    handles.addRect(handleRect.translated(m_d->transaction.originalBottomLeft()));
    handles.addRect(handleRect.translated(m_d->transaction.originalBottomRight()));
    handles.addRect(handleRect.translated(m_d->transaction.originalMiddleLeft()));
    handles.addRect(handleRect.translated(m_d->transaction.originalMiddleRight()));
    handles.addRect(handleRect.translated(m_d->transaction.originalMiddleTop()));
    handles.addRect(handleRect.translated(m_d->transaction.originalMiddleBottom()));

    QPointF rotationCenter = m_d->currentArgs.originalCenter() + m_d->currentArgs.rotationCenterOffset();
    QPointF dx(r + 3, 0);
    QPointF dy(0, r + 3);
    handles.addEllipse(rotationCenterRect.translated(rotationCenter));
    handles.moveTo(rotationCenter - dx);
    handles.lineTo(rotationCenter + dx);
    handles.moveTo(rotationCenter - dy);
    handles.lineTo(rotationCenter + dy);

    gc.save();

    //gc.setTransform(m_d->handlesTransform, true); <-- don't do like this!
    QPainterPath mappedHandles = m_d->handlesTransform.map(handles);

    QPen pen[2];
    pen[0].setWidth(1);
    pen[1].setWidth(2);
    pen[1].setColor(Qt::lightGray);

    for (int i = 1; i >= 0; --i) {
        gc.setPen(pen[i]);
        gc.drawPath(mappedHandles);
    }

    gc.restore();
}
void cShotTableItemDelegate::paint(QPainter *Painter,const QStyleOptionViewItem &option,const QModelIndex &index) const {
    int Height=ParentTable->rowHeight(0);
    int Width =ParentTable->columnWidth(0);

    if (ParentTable->DiaporamaObject==NULL) return;

    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    QImage    TempImg(Width,Height,QImage::Format_ARGB32_Premultiplied);
    QPainter  TempPainter;
    TempPainter.begin(&TempImg);

    // Fill background
    TempPainter.fillRect(QRectF(0,0,Width,Height),Transparent);

    int     CurCol  =index.column();
    int64_t Duration=0;
    bool    RedColor=false;
    int64_t Position=0;

    if ((CurCol>=0)&&(CurCol<ParentTable->DiaporamaObject->List.count())) {
        // Calc start position of this shot
        for (int i=1;i<=CurCol;i++) Position=Position+ParentTable->DiaporamaObject->List[i-1]->StaticDuration;

        // Calc duration of this shot
        Duration=ParentTable->DiaporamaObject->List[CurCol]->StaticDuration;

        // Define display color of duration (Red only if shot is the last and Position+Duration < DiaporamaObject's duration
        RedColor=((CurCol==ParentTable->DiaporamaObject->List.count()-1)&&(Position+Duration<ParentTable->DiaporamaObject->GetDuration()));
        if (RedColor) Duration=ParentTable->DiaporamaObject->GetDuration()-Position;

        // draw shot
        /*if (ParentTable->DiaporamaObject->Thumbnail) {
            delete ParentTable->DiaporamaObject->Thumbnail;
            ParentTable->DiaporamaObject->Thumbnail=NULL;
        }*/
        ParentTable->DiaporamaObject->DrawThumbnail(Width,Height,&TempPainter,0,0,CurCol);
    }

    // Draw selected box (if needed)
    if (CurCol==ParentTable->currentColumn()) {
        QPen Pen;
        Pen.setColor(Qt::blue);
        Pen.setWidth(6);
        TempPainter.setPen(Pen);
        TempPainter.setBrush(Qt::NoBrush);
        TempPainter.drawRect(3,3,Width-1-6,Height-1-6);
    }

    // Draw Drag & Drop inserting point (if needed)
    if ((ParentTable->IsDragOn==1)&&(CurCol!=ParentTable->DragItemSource)&&((CurCol==ParentTable->DragItemDest)||((CurCol==ParentTable->DragItemDest-1)&&(ParentTable->DragItemDest==ParentTable->DiaporamaObject->List.count())))) {
        TempPainter.save();
        QPen Pen;
        Pen.setColor(Qt::red);
        Pen.setStyle(Qt::SolidLine);
        Pen.setWidth(6);
        TempPainter.setPen(Pen);
        TempPainter.setBrush(Qt::NoBrush); //QBrush(QColor(WidgetSelection_Color)));
        TempPainter.setOpacity(0.5);
        TempPainter.setOpacity(0.5);
        if (CurCol==ParentTable->DragItemDest)  TempPainter.drawLine(3,      0,3,      Height);
            else                                TempPainter.drawLine(Width-3,0,Width-3,Height);
        TempPainter.setOpacity(1);
        TempPainter.restore();
    }

    // -------------------------- Draw shot duration
    QPen  Pen;
    QFont font= QApplication::font();
    int   FontFactor=((ParentTable->DiaporamaObject->Parent->ApplicationConfig->TimelineHeight-TIMELINEMINHEIGH)/20)*10;
    TempPainter.setFont(font);
    #ifdef Q_OS_WIN
    font.setPointSizeF(double(110+FontFactor)/double(TempPainter.fontMetrics().boundingRect("0").height()));                  // Scale font
    #else
    font.setPointSizeF((double(140+FontFactor)/double(TempPainter.fontMetrics().boundingRect("0").height()))*ScreenFontAdjust);// Scale font
    #endif
    TempPainter.setFont(font);
    Pen.setWidth(1);
    Pen.setStyle(Qt::SolidLine);
    QString ShotDuration=QTime(0,0,0,0).addMSecs(Duration).toString("hh:mm:ss.zzz");
    Pen.setColor(Qt::black);
    TempPainter.setPen(Pen);
    TempPainter.drawText(QRectF(6+1,6+1,Width-12,Height-12),ShotDuration,Qt::AlignHCenter|Qt::AlignTop);
    Pen.setColor(RedColor?Qt::red:Qt::white);
    TempPainter.setPen(Pen);
    TempPainter.drawText(QRectF(6,6,Width-12,Height-12),ShotDuration,Qt::AlignHCenter|Qt::AlignTop);

    // -------------------------- Draw shot position
    ShotDuration=QTime(0,0,0,0).addMSecs(Position+Duration).toString("hh:mm:ss.zzz");
    Pen.setColor(Qt::black);
    TempPainter.setPen(Pen);
    TempPainter.drawText(QRectF(6+1,6+1,Width-12,Height-12),ShotDuration,Qt::AlignRight|Qt::AlignBottom);
    Pen.setColor(RedColor?Qt::red:Qt::white);
    TempPainter.setPen(Pen);
    TempPainter.drawText(QRectF(6,6,Width-12,Height-12),ShotDuration,Qt::AlignRight|Qt::AlignBottom);

    TempPainter.end();
    Painter->drawImage(option.rect.x(),option.rect.y(),TempImg);

    QApplication::restoreOverrideCursor();
}
Example #30
0
void FilmstripTile::render(QPainter& painter, const Widgets::TileInfo& tileInfo, const QVariant& data)
{
    int w = painter.window().width();
    int h = painter.window().height();

    //   painter.drawLine(0,0,w-1,h-1);
    //   painter.drawLine(0,h,w-1,0);

    // TODO: Load fonts in advance??
    painter.setFont(QFont("helvetica", 18));

    if (!data.isNull())
    {
        if ((tileInfo.tileState & Widgets::TileInfo::TileStateSelected) ==
            Widgets::TileInfo::TileStateSelected)
            painter.setBrush(QBrush(QColor(Qt::darkGray).lighter(180),
                Qt::SolidPattern));
        else
            painter.setBrush(QBrush(QColor(Qt::darkGray),
                Qt::SolidPattern));
        // draw the tile
        painter.setPen(QColor(Qt::darkGray));
        painter.drawRect(0, 0, w - 2, h - 2);
        painter.setBrush(Qt::NoBrush);

        // draw the bevel
        painter.setPen(QColor(Qt::gray));
        // draw clock wise
        painter.drawLine(0, h - 1, 0, 0);     //left side
        painter.drawLine(0, 0, w - 1, 0);     // top side
        painter.setPen(QColor(Qt::black));
        painter.drawLine(w - 1, 0, w - 1, h - 1);    // right side
        painter.drawLine(w - 1, h - 1, 0, h - 1);     // bottom side

        Photo info = data.value<Photo>();

        // draw the id text
        painter.save();
        painter.setPen(QColor(Qt::darkGray).lighter(110));
        painter.setFont(QFont(QString("Verdana"), 24, QFont::Bold));
        int fontHeight = painter.fontMetrics().height();
        painter.drawText(5, fontHeight - 5, QString::number(info.id()));

        painter.restore();

        // draw the image.
        QImage image = info.libraryPreviewsRGB();
        QRect  photoFinalDimension;

        if (!image.isNull())
        {
            float ratio = 0.90f;
            int   wf    = (int)(w * ratio);     // width frame
            int   hf    = (int)(h * ratio);     // height frame

            photoFinalDimension = fitFrame(image.size(), QSize(wf, hf));

            // move the frame to the center
            photoFinalDimension.translate((w - wf) / 2, (h - hf) / 2);
            painter.drawImage(photoFinalDimension, image);

            // draw border around image
            painter.setPen(QColor(Qt::black));
            painter.drawRect(photoFinalDimension);
        }
        else
        {
            // TODO: draw missing image indicator
            painter.setPen(QColor(Qt::red));
            painter.drawLine(w / 2 - 15, h / 2 - 15, w / 2 + 15,
                h / 2 + 15);
            painter.drawLine(w / 2 - 15, h / 2 + 15, w / 2 + 15,
                h / 2 - 15);
        }
    }
    else
    {
        // TODO: draw missing picture instead of blue cross
        painter.setPen(QColor(Qt::blue));
        painter.drawLine(0, 0, w - 1, h - 1);
        painter.drawLine(0, h - 1, w - 1, 0);
    }
}