Exemple #1
0
void AuGrid::drawCrossGrid2(GridContext &gridGC)
{
    AuViewportGC *vpgc = gridGC.m_gc;
    QPainter *gc = new QPainter(vpgc->getGC());

    Device device = Display.getCurrent();
    Image pixelArray = new Image(device, gridGC.m_truexur - gridGC.m_truexll, 1);
    Image pixelArrayCross = new Image(device, gridGC.m_truexur - gridGC.m_truexll, 1);

    GC pixelArrayGC = new GC(pixelArray);
    GC pixelArrayCrossGC = new GC(pixelArrayCross);
    try {
        org.eclipse.swt.graphics.Color foregroundColor = new org.eclipse.swt.graphics.Color(device,
                m_color.getRed(), m_color.getGreen(), m_color.getBlue());
        Color vpBackgroundColor = gc.getBackground();
        org.eclipse.swt.graphics.Color backgroundColor = new org.eclipse.swt.graphics.Color(device,
            vpBackgroundColor.getRed(),	vpBackgroundColor.getGreen(), vpBackgroundColor.getBlue());

        pixelArrayGC.setForeground(foregroundColor);
        pixelArrayGC.setBackground(backgroundColor);
        pixelArrayGC.setLineStyle(STYLE_DOT);
        pixelArrayGC.fillRectangle(0, 0, gridGC.m_truexur - gridGC.m_truexll, 1);

        pixelArrayCrossGC.setForeground(foregroundColor);
        pixelArrayCrossGC.setBackground(backgroundColor);
        pixelArrayCrossGC.setLineStyle(STYLE_DOT);
        pixelArrayCrossGC.fillRectangle(0, 0, gridGC.m_truexur - gridGC.m_truexll, 1);
    } catch (Exception ex)
    {
        System.out.println("Unable to draw cross: " +
                ex.getMessage());
    }

    for (int i = 0; i <= gridGC.m_xnum; i++)
    {
        int x = gridGC.m_xll + (i * gridGC.m_dx);
        int y = gridGC.m_yll;

        // Convert world coordinates to device coordinates.
        VpCoord coord = ((VpGraphics2D)gc.m_viewport).worldToDev(x, y);

        if (((coord.m_x - 1) >= gridGC.m_truexll) && ((coord.m_x + 1) <= gridGC.m_truexur))
        {
            pixelArrayGC.drawOval(coord.m_x - gridGC.m_truexll - 1, 0, 1, 1);
            pixelArrayGC.drawOval(coord.m_x - gridGC.m_truexll, 0, 1, 1);
            pixelArrayGC.drawOval(coord.m_x - gridGC.m_truexll + 1, 0, 1, 1);
            pixelArrayCrossGC.drawOval(coord.m_x - gridGC.m_truexll, 0, 1, 1);
        }
    }

    for (int j = 0; j <= gridGC.m_ynum; j++)
    {
        int x = gridGC.m_xll;
        int y = gridGC.m_yll + (j * gridGC.m_dy);

        // Convert world coordinates to device coordinates.
        VpCoord coord = ((VpGraphics2D)gc.m_viewport).worldToDev(x, y);

        if (((coord.m_y - 1) >= gridGC.m_trueyll) && ((coord.m_y + 1) <= gridGC.m_trueyur))
        {
            try {
                gc.drawImage(pixelArrayCross, gridGC.m_truexll, coord.m_y - 1);
                gc.drawImage(pixelArray, gridGC.m_truexll, coord.m_y);
                gc.drawImage(pixelArrayCross, gridGC.m_truexll, coord.m_y + 1);
            } catch (Exception ex) {
                System.out.println("Unable to draw cross: " +
                    ex.getMessage());
            }
        }
    }

    // Flush graphics to display.
    //gc.flush();

    // Dispose of the cross image resources.
    pixelArrayGC.dispose();
    pixelArrayCrossGC.dispose();
    pixelArray.dispose();
    pixelArrayCross.dispose();
}
Exemple #2
0
int main(int argc, char **argv)
{
  if (argc < 5) {
    fprintf(stderr, "Usage: %s <maps.json> <map> <series> <max level> <base tile key>\n", argv[0]);
    return -1;
  }
  QFile rootFile(argv[1]);
  QString mapId(argv[2]);
  QString layerName(argv[3]);
  int maxLevel = atoi(argv[4]);
  QString rootTileKey("");
  if (argc == 5) {
    rootTileKey = QString(argv[5]);
  }

  RootData rootData(NULL);
  Map *map = rootData.maps()[mapId];


  int layer;
  if (!map->layerById(layerName, layer)) {
    fprintf(stderr, "Unknown layer %s\n", layerName.toLatin1().data());
    return -1;
  }
  Tile baseTile(layer, rootTileKey);
  int minLevel = baseTile.level();

  if (maxLevel <= baseTile.layer() || maxLevel > map->layer(layer).maxLevel()) {
    fprintf(stderr, "Invalid maximum level %d\n", maxLevel);
    return -1;    
  }

  printf("Merging layer %s from (%d, %d)@%d to %d\n", 
         map->layer(layer).name().toLatin1().data(),
         baseTile.x(), baseTile.y(), baseTile.level(), maxLevel);
         
  QRect baseRect(baseTile.x(), baseTile.y(), 1, 1);
  int tileSize = map->baseTileSize();
  
  for (int level = maxLevel - 1; level >= minLevel; level--) {
    printf("level %d\n", level);
    QRect tiles = map->rectAtLevel(baseRect, baseTile.level(), level);
    
    for (int y = tiles.top(); y <= tiles.bottom(); y++) {
      for (int x = tiles.left(); x <= tiles.right(); x++) {
        Tile to(x, y, level, layer);
        QImage image = QImage(256, 256, QImage::Format_RGB32);
        image.fill(QColor(255, 255, 255).rgb());
        QPainter p;
        bool isNull = true;
        QVector<QRgb> colorTable;
        p.begin(&image);
        p.setRenderHint(QPainter::SmoothPixmapTransform, true);
        for (int dy = 0; dy <= 1; dy++) {
          for (int dx = 0; dx <= 1; dx++) {
            Tile from(x * 2 + dx, y * 2 + dy, level + 1, layer);
            QString tilePath = map->tilePath(from);
            QImage tile(tilePath);
            if (!tile.isNull()) {
              isNull = false;
              QRect target(dx * tileSize / 2, dy * tileSize / 2, 
                           tileSize / 2, tileSize / 2);
              p.drawImage(target, tile);
              colorTable = tile.colorTable();
            }
          }
        }
        p.end();
        if (!isNull) {
          QImage indexImage = image.convertToFormat(QImage::Format_Indexed8, 
                                                    colorTable, Qt::ThresholdDither);
          indexImage.save(map->tilePath(to), "png");
        }
      }
    }

  }

  return 0;
}
void Matrix::print(const QString& fileName)
{
	QPrinter printer;
	printer.setColorMode (QPrinter::GrayScale);

	if (!fileName.isEmpty()){
	    printer.setCreator("QtiPlot");
	    printer.setOutputFormat(QPrinter::PdfFormat);
        printer.setOutputFileName(fileName);
	} else {
        QPrintDialog printDialog(&printer);
        if (printDialog.exec() != QDialog::Accepted)
            return;
    }
		printer.setFullPage( true );
		QPainter p;
		if ( !p.begin(&printer ) )
			return; // paint on printer
		int dpiy = printer.logicalDpiY();
		const int margin = (int) ( (1/2.54)*dpiy ); // 1 cm margins

        if (d_view_type == ImageView){
            p.drawImage (printer.pageRect(), d_matrix_model->renderImage());
            return;
        }

		QHeaderView *vHeader = d_table_view->verticalHeader();

		int rows = numRows();
		int cols = numCols();
		int height = margin;
		int i, vertHeaderWidth = vHeader->width();
		int right = margin + vertHeaderWidth;

		// print header
		p.setFont(QFont());
		QString header_label = d_matrix_model->headerData(0, Qt::Horizontal).toString();
		QRect br = p.boundingRect(br, Qt::AlignCenter, header_label);
		p.drawLine(right, height, right, height+br.height());
		QRect tr(br);

		for(i=0; i<cols; i++){
			int w = d_table_view->columnWidth(i);
			tr.setTopLeft(QPoint(right,height));
			tr.setWidth(w);
			tr.setHeight(br.height());
			header_label = d_matrix_model->headerData(i, Qt::Horizontal).toString();
			p.drawText(tr, Qt::AlignCenter, header_label,-1);
			right += w;
			p.drawLine(right, height, right, height+tr.height());

			if (right >= printer.width()-2*margin )
				break;
		}

		p.drawLine(margin + vertHeaderWidth, height, right-1, height);//first horizontal line
		height += tr.height();
		p.drawLine(margin, height, right-1, height);

		// print table values
		for(i=0;i<rows;i++){
			right = margin;
			QString cell_text = d_matrix_model->headerData(i, Qt::Horizontal).toString()+"\t";
			tr = p.boundingRect(tr, Qt::AlignCenter, cell_text);
			p.drawLine(right, height, right, height+tr.height());

			br.setTopLeft(QPoint(right,height));
			br.setWidth(vertHeaderWidth);
			br.setHeight(tr.height());
			p.drawText(br,Qt::AlignCenter,cell_text,-1);
			right += vertHeaderWidth;
			p.drawLine(right, height, right, height+tr.height());

			for(int j=0; j<cols; j++){
				int w = d_table_view->columnWidth (j);
				cell_text = text(i,j)+"\t";
				tr = p.boundingRect(tr,Qt::AlignCenter,cell_text);
				br.setTopLeft(QPoint(right,height));
				br.setWidth(w);
				br.setHeight(tr.height());
				p.drawText(br, Qt::AlignCenter, cell_text, -1);
				right += w;
				p.drawLine(right, height, right, height+tr.height());

				if (right >= printer.width()-2*margin )
					break;
			}
			height += br.height();
			p.drawLine(margin, height, right-1, height);

			if (height >= printer.height()-margin ){
				printer.newPage();
				height = margin;
				p.drawLine(margin, height, right, height);
			}
		}
}
Exemple #4
0
void NWaveformSlider::checkForUpdate()
{
    if (!m_waveBuilder)
        return;

    float builderPos;
    int builderIndex;
    m_waveBuilder->positionAndIndex(builderPos, builderIndex);

    if (m_oldSize != size() || m_oldBuilderIndex != builderIndex)
        m_needsUpdate = true;

    if ((builderPos != 0.0 && builderPos != 1.0) && m_timer->interval() != FAST_INTERVAL)
        m_timer->setInterval(FAST_INTERVAL);
    else
    if ((builderPos == 0.0 || builderPos == 1.0) && m_timer->interval() != IDLE_INTERVAL)
        m_timer->setInterval(IDLE_INTERVAL);

    if (m_needsUpdate) {
        QPainter painter;
        QImage waveImage;
        QImage backgroundImage;
        waveImage = backgroundImage = m_progressPlayingImage = m_progressPausedImage = m_remainingPlayingImage = m_remainingPausedImage = QImage(size(), QImage::Format_ARGB32_Premultiplied);

        m_oldBuilderPos = builderPos;
        m_oldBuilderIndex = builderIndex;
        m_oldSize = size();


        // waveform >>
        waveImage.fill(0);
        painter.begin(&waveImage);
        painter.setBrush(m_waveBackground);
        QPen wavePen;
        wavePen.setWidth(0);
        wavePen.setColor(m_waveBorderColor);
        painter.setPen(wavePen);

        painter.translate(1, 1);
        painter.scale((qreal)(width() - 1) / m_oldBuilderIndex * m_oldBuilderPos, (height() - 2) / 2);
        painter.translate(0, 1);

        QPainterPath pathPos;
        QPainterPath pathNeg;
        NWaveformPeaks *peaks = m_waveBuilder->peaks();
        for (int i = 0; i < m_oldBuilderIndex; ++i) {
            pathPos.lineTo(i, peaks->positive(i));
            pathNeg.lineTo(i, peaks->negative(i));
        }
        QPainterPath fullPath(pathNeg);
        fullPath.connectPath(pathPos.toReversed());
        fullPath.closeSubpath();
        painter.setRenderHint(QPainter::Antialiasing);
        painter.drawPath(fullPath);
        painter.end();
        // << waveform


        // main background >>
        painter.begin(&backgroundImage);
        backgroundImage.fill(0);
        painter.setPen(Qt::NoPen);
        painter.setBrush(m_background);
        painter.setRenderHint(QPainter::Antialiasing);
        painter.drawRoundedRect(rect(), m_radius, m_radius);
        painter.end();
        // << main background


        QList<QImage *> images; images << &m_progressPlayingImage << &m_progressPausedImage << &m_remainingPlayingImage << &m_remainingPausedImage;
        QList<QPainter::CompositionMode> modes; modes << m_playingComposition << m_pausedComposition << m_playingComposition << m_pausedComposition;
        QList<QBrush> brushes; brushes << m_progressPlayingBackground << m_progressPausedBackground << m_remainingPlayingBackground << m_remainingPausedBackground;
        for (int i = 0; i < images.size(); ++i) {
            painter.begin(images[i]);
            // background
            images[i]->fill(0);
            // + overlay
            painter.setPen(Qt::NoPen);
            painter.setBrush(brushes[i]);
            painter.setRenderHint(QPainter::Antialiasing);
            painter.drawRoundedRect(rect(), m_radius, m_radius);
            // + waveform
            painter.setCompositionMode(modes[i]);
            painter.drawImage(0, 0, waveImage);
            painter.setCompositionMode(QPainter::CompositionMode_DestinationOver);
            painter.drawImage(0, 0, backgroundImage);
            painter.end();
        }

        update();
        m_needsUpdate = false;
    }
}
Exemple #5
0
void BitmapImage::paintImage(QPainter& painter, QImage& image, QRect sourceRect, QRect destRect)
{
    painter.drawImage(QRect(mBounds.topLeft(), destRect.size()),
                      image,
                      sourceRect);
}
Exemple #6
0
void FontRenderer::placeImage(QPainter& p,ushort symbol,int x,int y) {
    p.drawImage(x,y,m_rendered.chars[symbol].img);
}
  void drawPixmap(const QImage& sprite, const aw::coord& c, QPainter& painter) {
	QSize size = sprite.size();
	painter.drawImage(QPoint((c.x*16)+(16-size.width()), (c.y*16)+(16-size.height())), sprite);
  }
Exemple #8
0
void  QmaxButton::createArrowBackground(QPainter &painter)
{
   // printf("Arrow BackGround2\n");
    QRect scaledRect;
    scaledRect = matrix.mapRect(QRect(0, 0, this->logicalSize.width(), this->logicalSize.height()));

    QImage image(scaledRect.width(), scaledRect.height(), QImage::Format_ARGB32_Premultiplied);
    image.fill(QColor(0, 0, 0, 0).rgba());
    //QPainter painter(image);
    painter.setRenderHint(QPainter::SmoothPixmapTransform);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(Qt::NoPen);
    painter.drawImage(0, 0, image);

    if(Colors::useEightBitPalette)
    {
        painter.setPen(QColor(120,120,120));
        if(this->m_nPressed)
            painter.setBrush(QColor(60,60,60));
        else if(this->m_nHighlight)
            painter.setBrush(QColor(100,100,100));
        else
            painter.setBrush(QColor(80,80,80));
    }
    else
    {
        QLinearGradient outlinebrush(0,0,0,scaledRect.height());
        QLinearGradient brush(0,0,0,scaledRect.height());

        brush.setSpread(QLinearGradient::PadSpread);
        QColor highlight(255,255,255,128);
        QColor shadow(0,0,0,70);
        QColor sunken(220,220,220,30);
        QColor normal1(88,88,89,255);
        QColor normal2(88,88,89,255);
        QColor normal3(0,0,200,10);
        QColor normal4(255,255,250,255);

         if(m_nType==3 || m_nType == 4)
         {
            normal1 = QColor(100,180,189,55);
            normal2 = QColor(100,180,189,255);
         }
        if(m_nPressed)
        {
            outlinebrush.setColorAt(0.0f,shadow);
            outlinebrush.setColorAt(1.0f,highlight);
            brush.setColorAt(1.0f,sunken);
            painter.setPen(Qt::NoPen);

        }
        else
        {
            outlinebrush.setColorAt(0.75f,shadow);
            outlinebrush.setColorAt(0.0f,highlight);
            brush.setColorAt(0.0f,normal2);
            if(m_nHighlight)
                brush.setColorAt(1.0f,normal1);
            painter.setPen(QPen(outlinebrush,1));
        }
        if(this->isEnabled()==false )
        {
            outlinebrush.setColorAt(1.0f,shadow);
            outlinebrush.setColorAt(0.0f,highlight);
            brush.setColorAt(0.0f,normal3);
            painter.setPen(QPen(outlinebrush,2));

        }
        if(m_nStatus )
        {
            outlinebrush.setColorAt(1.0f,shadow);
            outlinebrush.setColorAt(0.0f,highlight);
            brush.setColorAt(0.0f,normal2);
            painter.setPen(QPen(outlinebrush,1));
        }
        painter.setBrush(brush);

    }

    
   // painter.drawRect(0, 0, scaledRect.width(), scaledRect.height());

    float xOff = scaledRect.width() / 2;
    float yOff = scaledRect.height() / 2;
    float sizex = 5.0f * matrix.m11();
    float sizey = 3.5f * matrix.m22();
    if (m_nType == 3)
        sizey *= -1;
    QPainterPath path;
    path.moveTo(xOff, yOff + (5 * sizey));
    path.lineTo(xOff - (4 * sizex), yOff - (3 * sizey));
    path.lineTo(xOff + (4 * sizex), yOff - (3 * sizey));
    path.lineTo(xOff, yOff + (5 * sizey));
    painter.drawPath(path);

}
void ItemFoundAnimation::paint(QPainter& painter)
{
	painter.drawImage(currentX(), m_item->position().y(), m_item->image());
}
void paint(QPaintDevice* pd) {
    QPainter p;
    if (!p.begin(pd)) return;
    QPen pe(QColor("black"));
    pe.setWidthF(6.0);
    pe.setStyle(Qt::DashLine);
    p.setPen(pe);
    p.drawLine(QPointF(0,0),QPointF(100.0,100.0));
    pe.setColor("red");
    pe.setStyle(Qt::DotLine);
    p.setPen(pe);
    p.drawLine(QPointF(0,0),QPointF(50.0,25.0));
    pe.setColor("green");
    pe.setStyle(Qt::SolidLine);
    p.setPen(pe);
    p.drawLine(QPointF(0,0),QPointF(25.0,50.0));
    pe.setColor("blue");
    p.setPen(pe);
    p.drawText(50,10, QString("Hello World!"));
    p.drawLine(50,10,55,15);
    QFont f;
    QImage img(QString("qfe_plotterexportercairo.png"));
    pe.setWidthF(0.5);
    p.setPen(pe);
    p.drawImage(QRectF(50,25,50,50), img);
    //p.drawRect(QRectF(50,25,50,50));
    p.drawImage(QRectF(25,50,15,10), img);
    //p.drawRect(QRectF(25,50,15,10));
    p.drawImage(QRectF(225,50,100,100), img, QRect(5,5,12,12));
    p.drawRect(QRectF(125,50,15,10));
    pe.setWidthF(2);
    pe.setColor("red");
    p.setPen(pe);
    f.setFamily("Times New Roman");
    f.setPointSizeF(10);
    p.setFont(f);
    p.drawText(50,30, QString("Hello World!"));
    p.drawLine(50,30,55,35);

    f.setFamily("Arial");
    f.setPointSizeF(16);
    p.setFont(f);
    p.drawText(250,30, QString("Unicode-test: ")+QChar(0x2190)+QChar(0x2591)+QChar(0x2665)+QChar(0x039B)+QChar(0x03B6));
    p.drawLine(250,30,255,35);

    pe.setWidthF(1);
    p.setPen(pe);
    QBrush b(QColor("salmon"));
    p.fillRect(QRectF(100,10,50,50), b);
    p.drawRect(QRectF(100,10,50,50));
    QColor c=b.color();
    c.setAlphaF(0.5);
    b.setColor(c);
    pe.setWidthF(5);
    p.setPen(pe);
    p.setBrush(b);
    p.drawEllipse(QRectF(130,40,50,30));
    //p.drawRect(QRectF(130,40,50,30));
    QPolygonF poly;
    for (int phi=0; phi<60; phi++) {
        double p=double(phi)/20.0*M_PI;
        poly<<QPointF(50.0+cos(p)*35.0*double(phi)/60.0, 50.0-sin(p)*35.0*double(phi)/60.0);
    }

    p.setClipRect(0,0,200,50);

    pe.setWidthF(1);
    p.setPen(pe);
    p.drawPolygon(poly);
    pe.setColor("red");
    pe.setStyle(Qt::DashDotDotLine);
    p.setPen(pe);
    p.setClipping(false);
    p.drawPolyline(poly);


    p.end();
}
Exemple #11
0
void  QmaxButton::createButton(QPainter &painter)
{
    QRect scaledRect;
    scaledRect = matrix.mapRect(QRect(0,0,this->logicalSize.width(),this->logicalSize.height()));
    QImage bg(this->m_strImage);
    painter.setRenderHint(QPainter::SmoothPixmapTransform);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(Qt::NoPen);
    QLinearGradient brush1(0,0,0,scaledRect.height());
    painter.drawImage(-2, -2, bg);


    if(Colors::useEightBitPalette)
    {
        painter.setPen(QColor(120,120,120));
        if(this->m_nPressed)
            painter.setBrush(QColor(60,60,60));
        else if(this->m_nHighlight)
            painter.setBrush(QColor(100,100,100));
        else
            painter.setBrush(QColor(80,80,80));
    }
    else
    {
        QLinearGradient outlinebrush(0,0,0,scaledRect.height());
        QLinearGradient brush(0,0,0,scaledRect.height());

        brush.setSpread(QLinearGradient::PadSpread);
        QColor highlight(255,255,255,128);
        QColor shadow(0,0,0,70);
        QColor sunken(220,220,220,30);
        QColor normal1(255,255,245,60);
        QColor normal2(255,255,235,10);
        QColor normal3(200,200,200,10);
        QColor normal4(255,255,250,255);

         if(m_nType && m_nType != 5  )
         {
            normal1 = QColor(200,170,160,50);
            normal2 = QColor(50,10,0,50);
         }
        if(m_nPressed)
        {
            outlinebrush.setColorAt(0.0f,shadow);
            outlinebrush.setColorAt(1.0f,highlight);
            brush.setColorAt(1.0f,sunken);
            painter.setPen(Qt::NoPen);

        }
        else
        {
            outlinebrush.setColorAt(1.0f,shadow);
            outlinebrush.setColorAt(0.0f,highlight);
            brush.setColorAt(0.0f,normal1);
            if(m_nHighlight)
                brush.setColorAt(1.0f,normal2);
            painter.setPen(QPen(outlinebrush,1));
        }
        if(this->isEnabled()==false )
        {
            outlinebrush.setColorAt(1.0f,shadow);
            outlinebrush.setColorAt(0.0f,highlight);
            brush.setColorAt(0.0f,normal3);
            painter.setPen(QPen(outlinebrush,1));

        }
        if(m_nStatus )
        {
            outlinebrush.setColorAt(1.0f,shadow);
            outlinebrush.setColorAt(0.0f,highlight);
            brush.setColorAt(0.0f,normal4);
            painter.setPen(QPen(outlinebrush,1));
        }
        painter.setBrush(brush);

    }


    if(m_nType == 1)
        painter.drawRect(0,0,scaledRect.width(),scaledRect.height());
    else if(m_nType == 0)
        painter.drawRoundedRect(0,0,scaledRect.width(),scaledRect.height(),40.0,40.0,Qt::RelativeSize);
    else if(m_nType == 5)
        painter.drawEllipse(0,0,scaledRect.width(),scaledRect.height());
    QFont font( "DejaVu Sans" );
    font.setPointSize( 12 );
    painter.setFont( font );
    brush1.setColorAt(1.0f,QColor(255,255,255,255));
    if(this->isEnabled()==false)
    {
        brush1.setColorAt(1.0f,QColor(200,200,200,100));
    }
    painter.setPen(QPen(brush1,1));
    painter.setBrush(brush1);
    QFontMetrics fMetrics = painter.fontMetrics();
    QSize sz = fMetrics.size( Qt::TextWordWrap, m_strText );
    QRectF txtRect( scaledRect.center(), sz );
    int xPoint = (scaledRect.width()/2)- ((m_strText.count()/2)*10);
    int yPoint = scaledRect.height()/2;
    painter.drawText(xPoint,yPoint,m_strText);
}
void CanvasRenderingContext2D::drawImage(HTMLCanvasElement* canvas, const FloatRect& srcRect,
    const FloatRect& dstRect, ExceptionCode& ec)
{
    ASSERT(canvas);

    ec = 0;

    FloatRect srcCanvasRect = FloatRect(FloatPoint(), canvas->size());
    if (!(srcCanvasRect.contains(srcRect) && srcRect.width() >= 0 && srcRect.height() >= 0 
            && dstRect.width() >= 0 && dstRect.height() >= 0)) {
        ec = INDEX_SIZE_ERR;
        return;
    }

    if (srcRect.isEmpty() || dstRect.isEmpty())
        return;

    GraphicsContext* c = drawingContext();
    if (!c)
        return;
        
    FloatRect sourceRect = c->roundToDevicePixels(srcRect);
    FloatRect destRect = c->roundToDevicePixels(dstRect);
        
    // FIXME: Do this through platform-independent GraphicsContext API.
#if PLATFORM(CG)
    CGImageRef platformImage = canvas->createPlatformImage();
    if (!platformImage)
        return;

    willDraw(destRect);

    float iw = CGImageGetWidth(platformImage);
    float ih = CGImageGetHeight(platformImage);
    if (sourceRect.x() == 0 && sourceRect.y() == 0 && iw == sourceRect.width() && ih == sourceRect.height()) {
        // Fast path, yay!
        CGContextDrawImage(c->platformContext(), destRect, platformImage);
    } else {
        // Slow path, boo!
        // Create a new bitmap of the appropriate size and then draw that into our context.

        size_t csw = static_cast<size_t>(ceilf(sourceRect.width()));
        size_t csh = static_cast<size_t>(ceilf(sourceRect.height()));

        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        size_t bytesPerRow = csw * 4;
        void* buffer = fastMalloc(csh * bytesPerRow);

        CGContextRef clippedSourceContext = CGBitmapContextCreate(buffer, csw, csh,
            8, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
        CGColorSpaceRelease(colorSpace);
        CGContextTranslateCTM(clippedSourceContext, -sourceRect.x(), -sourceRect.y());
        CGContextDrawImage(clippedSourceContext, CGRectMake(0, 0, iw, ih), platformImage);

        CGImageRef clippedSourceImage = CGBitmapContextCreateImage(clippedSourceContext);
        CGContextRelease(clippedSourceContext);

        CGContextDrawImage(c->platformContext(), destRect, clippedSourceImage);
        CGImageRelease(clippedSourceImage);
        
        fastFree(buffer);
    }

    CGImageRelease(platformImage);
#elif PLATFORM(QT)
    QImage px = canvas->createPlatformImage();
    if (px.isNull())
        return;
    willDraw(dstRect);
    QPainter* painter = static_cast<QPainter*>(c->platformContext());
    painter->drawImage(dstRect, px, srcRect);
#elif PLATFORM(CAIRO)
    cairo_surface_t* image = canvas->createPlatformImage();
    willDraw(dstRect);
    cairo_t* cr = c->platformContext();
    cairo_save(cr);
    cairo_set_source_surface(cr, image, srcRect.x(), srcRect.y());
    cairo_rectangle(cr, dstRect.x(), dstRect.y(), dstRect.width(), dstRect.height());
    cairo_fill(cr);
    cairo_restore(cr);
#endif
}
Exemple #13
0
void FDialogPreview::GenPreview(QString name)
{
	QPixmap pm;
	QString Buffer = "";
	updtPix();
	if (name.isEmpty())
		return;
	QFileInfo fi = QFileInfo(name);
	if (fi.isDir())
		return;
	int w = pixmap()->width();
	int h = pixmap()->height();
	bool mode = false;
	QString ext = fi.suffix().toLower();
	QString formatD(FormatsManager::instance()->extensionListForFormat(FormatsManager::IMAGESIMGFRAME, 1));
 	QStringList formats = formatD.split("|");
	formats.append("pat");
	
	QStringList allFormatsV = LoadSavePlugin::getExtensionsForPreview(FORMATID_ODGIMPORT);
	if (ext.isEmpty())
		ext = getImageType(name);
	if (formats.contains(ext.toUtf8()))
	{
		ScImage im;
		//No doc to send data anyway, so no doc to get into scimage.
		CMSettings cms(0, "", Intent_Perceptual);
		cms.allowColorManagement(false);
		if (im.loadPicture(name, 1, cms, ScImage::Thumbnail, 72, &mode))
		{
			int ix,iy;
			if ((im.imgInfo.exifDataValid) && (!im.imgInfo.exifInfo.thumbnail.isNull()))
			{
				ix = im.imgInfo.exifInfo.width;
				iy = im.imgInfo.exifInfo.height;
			}
			else
			{
				ix = im.width();
				iy = im.height();
			}
			int xres = im.imgInfo.xres;
			int yres = im.imgInfo.yres;
			QString tmp = "";
			QString tmp2 = "";
			QImage im2 = im.scaled(w - 5, h - 44, Qt::KeepAspectRatio, Qt::SmoothTransformation);
			QPainter p;
			QBrush b(QColor(205,205,205), loadIcon("testfill.png"));
			// Qt4 FIXME imho should be better
			pm = *pixmap();
			p.begin(&pm);
			p.fillRect(0, 0, w, h-44, b);
			p.fillRect(0, h-44, w, 44, QColor(255, 255, 255));
			p.drawImage((w - im2.width()) / 2, (h - 44 - im2.height()) / 2, im2);
			p.drawText(2, h-29, tr("Size:")+" "+tmp.setNum(ix)+" x "+tmp2.setNum(iy));
			p.drawText(2, h-17, tr("Resolution:")+" "+tmp.setNum(xres)+" x "+tmp2.setNum(yres)+" "+ tr("DPI"));
			QString cSpace;
			if ((extensionIndicatesPDF(ext) || extensionIndicatesEPSorPS(ext)) && (im.imgInfo.type != ImageType7))
				cSpace = tr("Unknown");
			else
				cSpace=colorSpaceText(im.imgInfo.colorspace);
			p.drawText(2, h-5, tr("Colorspace:")+" "+cSpace);
			p.end();
			setPixmap(pm);
			repaint();
		}
	}
	else if (allFormatsV.contains(ext.toUtf8()))
	{
		FileLoader *fileLoader = new FileLoader(name);
		int testResult = fileLoader->TestFile();
		delete fileLoader;
		if ((testResult != -1) && (testResult >= FORMATID_ODGIMPORT))
		{
			const FileFormat * fmt = LoadSavePlugin::getFormatById(testResult);
			if( fmt )
			{
				QImage im = fmt->readThumbnail(name);
				if (!im.isNull())
				{
					QString desc = tr("Size:")+" ";
					desc += value2String(im.text("XSize").toDouble(), PrefsManager::instance()->appPrefs.docSetupPrefs.docUnitIndex, true, true);
					desc += " x ";
					desc += value2String(im.text("YSize").toDouble(), PrefsManager::instance()->appPrefs.docSetupPrefs.docUnitIndex, true, true);
					im = im.scaled(w - 5, h - 21, Qt::KeepAspectRatio, Qt::SmoothTransformation);
					QPainter p;
					QBrush b(QColor(205,205,205), loadIcon("testfill.png"));
					pm = *pixmap();
					p.begin(&pm);
					p.fillRect(0, 0, w, h-21, b);
					p.fillRect(0, h-21, w, 21, QColor(255, 255, 255));
					p.drawImage((w - im.width()) / 2, (h - 21 - im.height()) / 2, im);
					p.drawText(2, h-5, desc);
					p.end();
					setPixmap(pm);
					repaint();
				}
			}
		}
	}
	else if (ext.toUtf8() == "sml")
	{
		QPixmap pmi;
		QByteArray cf;
		if (loadRawText(name, cf))
		{
			QString f = QString::fromUtf8(cf.data());
			StencilReader *pre = new StencilReader();
			pmi = pre->createPreview(f);
			QImage im = pmi.toImage();
			im = im.scaled(w - 5, h - 21, Qt::KeepAspectRatio, Qt::SmoothTransformation);
			QPainter p;
			QBrush b(QColor(205,205,205), loadIcon("testfill.png"));
			pm = *pixmap();
			p.begin(&pm);
			p.fillRect(0, 0, w, h-21, b);
			p.fillRect(0, h-21, w, 21, QColor(255, 255, 255));
			p.drawImage((w - im.width()) / 2, (h - 21 - im.height()) / 2, im);
			QString desc = tr("Size:")+QString(" %1 x %2").arg(im.width()).arg(im.height());
			p.drawText(2, h-5, desc);
			p.end();
			setPixmap(pm);
			repaint();
			delete pre;
		}
	}
	else if (ext.toUtf8() == "shape")
	{
		QByteArray cf;
		if (loadRawText(name, cf))
		{
			QString f = QString::fromUtf8(cf.data());
			StencilReader *pre = new StencilReader();
			QString f2 = pre->createShape(f);
			ScPreview *pre2 = new ScPreview();
			QImage im = pre2->createPreview(f2);
			im = im.scaled(w - 5, h - 21, Qt::KeepAspectRatio, Qt::SmoothTransformation);
			QPainter p;
			QBrush b(QColor(205,205,205), loadIcon("testfill.png"));
			pm = *pixmap();
			p.begin(&pm);
			p.fillRect(0, 0, w, h-21, b);
			p.fillRect(0, h-21, w, 21, QColor(255, 255, 255));
			p.drawImage((w - im.width()) / 2, (h - 21 - im.height()) / 2, im);
			QString desc = tr("Size:")+QString(" %1 x %2").arg(im.width()).arg(im.height());
			p.drawText(2, h-5, desc);
			p.end();
			setPixmap(pm);
			repaint();
			delete pre;
			delete pre2;
		}
	}
	else if (ext.toUtf8() == "sce")
	{
		QByteArray cf;
		if (loadRawText(name, cf))
		{
			QString f;
			if (cf.left(16) == "<SCRIBUSELEMUTF8")
				f = QString::fromUtf8(cf.data());
			else
				f = cf.data();
			ScPreview *pre = new ScPreview();
			QImage im = pre->createPreview(f);
			im = im.scaled(w - 5, h - 21, Qt::KeepAspectRatio, Qt::SmoothTransformation);
			QPainter p;
			QBrush b(QColor(205,205,205), loadIcon("testfill.png"));
			pm = *pixmap();
			p.begin(&pm);
			p.fillRect(0, 0, w, h-21, b);
			p.fillRect(0, h-21, w, 21, QColor(255, 255, 255));
			p.drawImage((w - im.width()) / 2, (h - 21 - im.height()) / 2, im);
			QString desc = tr("Size:")+QString(" %1 x %2").arg(im.width()).arg(im.height());
			p.drawText(2, h-5, desc);
			p.end();
			setPixmap(pm);
			repaint();
			delete pre;
		}
	}
	else
	{
		ScSlaInfoReader slaInfos;
		if (slaInfos.readInfos(name))
		{
			QString Title = tr("Title:")+" ";
			QString ti2 = slaInfos.title();
			if (ti2.isEmpty())
				ti2= tr("No Title");
			Title += ti2+"\n";
			QString Author = tr("Author:")+" ";
			QString au2 = slaInfos.author();
			if (au2.isEmpty())
				au2 = tr("Unknown");
			Author += au2+"\n";
			QString Format =  tr("File Format:")+" ";
			QString fm2 = slaInfos.format();
			if (fm2.isEmpty())
				fm2 = tr("Unknown");
			Format += fm2;
			setText( tr("Scribus Document")+"\n\n"+Title+Author+Format);
		}
		else  if ((ext == "txt") || (ext == "html") || (ext == "xml"))
		{
			if (loadText(name, &Buffer))
				setText(Buffer.left(200));
		}
	}
}
Exemple #14
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));


    QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");

    //maBase=new QSqlDatabase(db);

    db.setHostName("172.16.63.111");
    db.setDatabaseName("dbtrouxNewWorld");
    db.setUserName("troux");
    db.setPassword("PscX57Q16");
    bool ok = db.open();
    if(!ok)
    {
        cout<<"Connection impossible"<<endl;
    }
    else
    {
        cout<<"Connection réussie"<<endl;
    }

    Connexion co;
    QVector<int> idUser = co.getTabIdUser();
    int nbUser = idUser.size();



    for(int comp=0; comp<nbUser; comp++)
    {
        QString userNom = co.getUserNom(idUser[comp]);
        QString userPrenom = co.getUserPrenom(idUser[comp]);
        QVector<int> numPDV = co.getUserTabPointDeVente(idUser[comp]);
        QVector<int> numProduit;
        for(int compPDV=0; compPDV<numPDV.size(); compPDV++)
        {
            QVector<int> tabInstNumProd = co.getProdByPDV(numPDV[compPDV]);
            for(int compProd=0; compProd < tabInstNumProd.size(); compProd++)
            {
                bool uniqueNumProd = true;
                for(int compVerifDoubleProd=0; compVerifDoubleProd < numProduit.size(); compVerifDoubleProd++)
                {
                    if(numProduit[compVerifDoubleProd] == tabInstNumProd[compProd])
                    {
                        uniqueNumProd = false;
                    }
                }
                if(uniqueNumProd){
                    numProduit.push_back(tabInstNumProd[compProd]);
                }
            }
        }
        QVector<int> numRayon = co.getTabRayon(numProduit);
        QVector<int> numCategorie = co.getTabCategorie(numRayon);

        QPrinter printer(QPrinter::HighResolution); //create your QPrinter (don't need to be high resolution, anyway)
        printer.setFullPage(QPrinter::A4);
        printer.setOutputFormat(QPrinter::NativeFormat);
        printer.setOutputFileName("pdfClient/"+ QString::number(idUser[comp]) +".pdf");


        QPen pen;
        int decalage = -100;
        int tailleImage = 1800;
        QPainter painter;
        painter.begin(&printer);
        QRectF rectangle(700, decalage,1000,900);
        QImage monImage;
        monImage.load("images/presentation/logoNw.jpg");
        painter.drawImage(rectangle, monImage);
        QRectF rectangle2(1200, decalage,8000,1000);
        QImage monImage2;
        monImage2.load("images/presentation/ecritureNw.png");
        painter.drawImage(rectangle2, monImage2);
        decalage += 2000;
        painter.setFont(QFont("Arial",15));
        painter.drawText(0, decalage, userNom +" "+ userPrenom +",");
        decalage += 250;
        painter.drawText(0, decalage,"Bienvenue sur votre catalogue personnalisé ");
        decalage += 400;
        painter.setFont(QFont("Arial",9));
        painter.drawText(0, decalage, "Liste des points de vente associés :");
        decalage += 200;
        pen.setWidth(10);
        painter.setPen(pen);
        for(int compNbPDV=0; compNbPDV<numPDV.size(); compNbPDV++)
        {
            painter.drawRect(0, decalage, 3000, 300);
            painter.drawText(100, decalage+200, QString::number(compNbPDV+1)+ " : " +co.getNomPDV(numPDV[compNbPDV]));
            painter.drawText(2000, decalage+200, QString::number(co.getProdByPDV(numPDV[compNbPDV]).size())+ " Produits");
            decalage += 300;
        }
        decalage += 1000;
        painter.setFont(QFont("Arial",12));
        painter.drawText(0, decalage,"Nous vous proposerons cette semaine "+QString::number(numProduit.size()) +" produits parmi les "+ QString::number(numPDV.size()) +" points de vente choisis.");
        decalage += 650;

        foreach(const int &idCategorie, numCategorie)
        {
            painter.drawText(0, decalage, co.getCategorieName(idCategorie));
            decalage += 200;
            foreach(const int &idRayon, numRayon)
            {
                if(co.getCategorieByRayon(idRayon) == idCategorie)
                {
                    painter.drawText(500,decalage, co.getRayonName(idRayon));
                    decalage += 500;
                    int decalageV = 1000;
                    foreach(const int &idProduit, numProduit)
                    {
                        if(co.getRayonByProd(idProduit) == idRayon)
                        {
                            painter.drawText(decalageV, decalage-300, co.getProdName(idProduit));
                            QRectF rectangle(decalageV, decalage-100, tailleImage, tailleImage);
                            QImage monImage;
                            monImage.load("images/produit/"+ QString::number(idProduit) +".png");
                            painter.drawImage(rectangle, monImage);
                            pen.setColor(Qt::magenta);
                            painter.setPen(pen);
                            painter.setFont(QFont("Arial",10));
                            painter.drawText(decalageV, decalage+tailleImage+100, QString::number(co.getPriceByIdProd(idProduit)) +" € par "+ co.getUniteByIdProd(idProduit));
                            QColor color;
                            color.setNamedColor("#04B404");
                            pen.setColor(color);
                            painter.setPen(pen);
                            painter.drawText(decalageV, decalage+tailleImage+300, "Restant : "+ QString::number(co.getQteRestanteByIdProd(idProduit)));
                            QVector<int> tabAssociatePDV = co.getTabPDVByIdProd(numPDV, idProduit);
                            QString letterPDV = "| ";
                            for(int compNoAPDV=0; compNoAPDV<tabAssociatePDV.size(); compNoAPDV++)
                            {
                                letterPDV += QString::number(compNoAPDV+1)+" | ";
                            }
                            pen.setColor(Qt::blue);
                            painter.setPen(pen);
                            painter.drawText(decalageV, decalage+tailleImage+500, "Disponible à : "+ letterPDV);
                            pen.setColor(Qt::black);
                            painter.setPen(pen);
                            painter.setFont(QFont("Arial",12));

                            decalageV += tailleImage+300;

                        }
                    }
                    decalage += tailleImage+900;
                    if(decalage > 10500){
                        printer.newPage();
                        decalage = 0;
                    }
                }
            }
        }
Exemple #15
0
void QgsSimpleMarkerSymbolLayerV2::renderPoint( const QPointF& point, QgsSymbolV2RenderContext& context )
{
  QPainter *p = context.renderContext().painter();
  if ( !p )
  {
    return;
  }

  //offset
  double offsetX = 0;
  double offsetY = 0;
  markerOffset( context, offsetX, offsetY );
  QPointF off( offsetX, offsetY );

  //angle
  double angle = mAngle;
  if ( mAngleExpression )
  {
    angle = mAngleExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble();
  }
  if ( angle )
    off = _rotatedOffset( off, angle );

  //data defined shape?
  if ( mNameExpression )
  {
    QString name = mNameExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString();
    if ( !prepareShape( name ) ) // drawing as a polygon
    {
      preparePath( name ); // drawing as a painter path
    }
  }

  if ( mUsingCache )
  {
    // we will use cached image
    QImage &img = context.selected() ? mSelCache : mCache;
    double s = img.width() / context.renderContext().rasterScaleFactor();
    p->drawImage( QRectF( point.x() - s / 2.0 + off.x(),
                          point.y() - s / 2.0 + off.y(),
                          s, s ), img );
  }
  else
  {
    QMatrix transform;

    // move to the desired position
    transform.translate( point.x() + off.x(), point.y() + off.y() );

    QgsExpression *sizeExpression = expression( "size" );
    bool hasDataDefinedSize = context.renderHints() & QgsSymbolV2::DataDefinedSizeScale || sizeExpression;

    // resize if necessary
    if ( hasDataDefinedSize )
    {
      double scaledSize = mSize;
      if ( sizeExpression )
      {
        scaledSize = sizeExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble();
      }
      scaledSize *= QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mSizeUnit );

      switch ( mScaleMethod )
      {
        case QgsSymbolV2::ScaleArea:
          scaledSize = sqrt( scaledSize );
          break;
        case QgsSymbolV2::ScaleDiameter:
          break;
      }

      double half = scaledSize / 2.0;
      transform.scale( half, half );
    }

    bool hasDataDefinedRotation = context.renderHints() & QgsSymbolV2::DataDefinedRotation || mAngleExpression;
    if ( angle != 0 && hasDataDefinedRotation )
      transform.rotate( angle );

    QgsExpression* colorExpression = expression( "color" );
    QgsExpression* colorBorderExpression = expression( "color_border" );
    QgsExpression* outlineWidthExpression = expression( "outline_width" );
    if ( colorExpression )
    {
      mBrush.setColor( QgsSymbolLayerV2Utils::decodeColor( colorExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString() ) );
    }
    if ( colorBorderExpression )
    {
      mPen.setColor( QgsSymbolLayerV2Utils::decodeColor( colorBorderExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString() ) );
      mSelPen.setColor( QgsSymbolLayerV2Utils::decodeColor( colorBorderExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString() ) );
    }
    if ( outlineWidthExpression )
    {
      double outlineWidth = outlineWidthExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble();
      mPen.setWidthF( outlineWidth * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mOutlineWidthUnit ) );
      mSelPen.setWidthF( outlineWidth * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mOutlineWidthUnit ) );
    }

    p->setBrush( context.selected() ? mSelBrush : mBrush );
    p->setPen( context.selected() ? mSelPen : mPen );

    if ( !mPolygon.isEmpty() )
      p->drawPolygon( transform.map( mPolygon ) );
    else
      p->drawPath( transform.map( mPath ) );
  }
}
Exemple #16
0
void ImageLoader::run()
{
    QString fn = m_url.toLocalFile();
    int pos = fn.lastIndexOf('.');
    QString ext;
    if (pos != -1)
        ext = fn.mid(pos).toUpper();
    if (ext.isEmpty() ||
            !QImageReader::supportedImageFormats().contains(ext.toLocal8Bit()))
        ext = QString();
    QFile f(fn);
    if (!f.open(QIODevice::ReadOnly))
    {
        qWarning("Could not read: %s", qPrintable(m_url.path()));
        return;
    }
    QByteArray bytes;
    while (!f.atEnd())
    {
        QThread::yieldCurrentThread();
        bytes.append(f.read(1024));
    }
    QThread::yieldCurrentThread();
    QImage im = ext.isEmpty() ? QImage::fromData(bytes)
                : QImage::fromData(bytes, qPrintable(ext));
    if (im.isNull())
        return;
    QString p = m_url.path();
    p = p.section("/", -1);
    int max = qMax(im.width(), im.height());
    QImage frm;
    if (max <= 64)
        frm = QImage(QSize(64, 64), QImage::Format_ARGB32);
    else if (max <= 128)
        frm = QImage(QSize(128, 128), QImage::Format_ARGB32);
    else if (max <= 256)
        frm = QImage(QSize(256, 256), QImage::Format_ARGB32);
    else if (max <= 512)
        frm = QImage(QSize(512, 512), QImage::Format_ARGB32);
    else
        frm = QImage(QSize(1024, 1024), QImage::Format_ARGB32);
    frm.fill(qRgba(0, 0, 0, 0));
    QPainter ptr;
    ptr.begin(&frm);
    ptr.setBackgroundMode(Qt::TransparentMode);
    QRect r;
    if (max > 1024)
    {
        if (max == im.width())
        {
            float h = float(1024) * float(im.height()) / float(im.width());
            r.setSize(QSize(1024, h));
        }
        else
        {
            float w = float(1024) * float(im.width()) / float(im.height());
            r.setSize(QSize(w, 1024));
        }
    }
    else
    {
        r.setSize(im.size());
    }
    int left = (frm.width() - r.width()) / 2;
    int top = (frm.height() - r.height()) / 2;
    r.moveTopLeft(QPoint(left, top));
    QThread::yieldCurrentThread();
    ptr.drawImage(r, im);
    ptr.end();
    emit imageLoaded(frm);
}
Exemple #17
0
void QgsSvgMarkerSymbolLayerV2::renderPoint( const QPointF& point, QgsSymbolV2RenderContext& context )
{
  QPainter *p = context.renderContext().painter();
  if ( !p )
    return;

  double size = mSize;
  QgsExpression* sizeExpression = expression( "size" );
  bool hasDataDefinedSize = context.renderHints() & QgsSymbolV2::DataDefinedSizeScale || sizeExpression;

  if ( sizeExpression )
  {
    size = sizeExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble();
  }
  size *= QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mSizeUnit );

  if ( hasDataDefinedSize )
  {
    switch ( mScaleMethod )
    {
      case QgsSymbolV2::ScaleArea:
        size = sqrt( size );
        break;
      case QgsSymbolV2::ScaleDiameter:
        break;
    }
  }

  //don't render symbols with size below one or above 10,000 pixels
  if (( int )size < 1 || 10000.0 < size )
  {
    return;
  }

  p->save();

  //offset
  double offsetX = 0;
  double offsetY = 0;
  markerOffset( context, offsetX, offsetY );
  QPointF outputOffset( offsetX, offsetY );

  double angle = mAngle;
  QgsExpression* angleExpression = expression( "angle" );
  if ( angleExpression )
  {
    angle = angleExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble();
  }
  if ( angle )
    outputOffset = _rotatedOffset( outputOffset, angle );
  p->translate( point + outputOffset );

  bool rotated = !qgsDoubleNear( angle, 0 );
  bool drawOnScreen = qgsDoubleNear( context.renderContext().rasterScaleFactor(), 1.0, 0.1 );
  if ( rotated )
    p->rotate( angle );

  QString path = mPath;
  QgsExpression* nameExpression = expression( "name" );
  if ( nameExpression )
  {
    path = nameExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString();
  }

  double outlineWidth = mOutlineWidth;
  QgsExpression* outlineWidthExpression = expression( "outline_width" );
  if ( outlineWidthExpression )
  {
    outlineWidth = outlineWidthExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble();
  }

  QColor fillColor = mFillColor;
  QgsExpression* fillExpression = expression( "fill" );
  if ( fillExpression )
  {
    fillColor = QgsSymbolLayerV2Utils::decodeColor( fillExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString() );
  }

  QColor outlineColor = mOutlineColor;
  QgsExpression* outlineExpression = expression( "outline" );
  if ( outlineExpression )
  {
    outlineColor = QgsSymbolLayerV2Utils::decodeColor( outlineExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString() );
  }


  bool fitsInCache = true;
  bool usePict = true;
  double hwRatio = 1.0;
  if ( drawOnScreen && !rotated )
  {
    usePict = false;
    const QImage& img = QgsSvgCache::instance()->svgAsImage( path, size, fillColor, outlineColor, outlineWidth,
                        context.renderContext().scaleFactor(), context.renderContext().rasterScaleFactor(), fitsInCache );
    if ( fitsInCache && img.width() > 1 )
    {
      //consider transparency
      if ( !qgsDoubleNear( context.alpha(), 1.0 ) )
      {
        QImage transparentImage = img.copy();
        QgsSymbolLayerV2Utils::multiplyImageOpacity( &transparentImage, context.alpha() );
        p->drawImage( -transparentImage.width() / 2.0, -transparentImage.height() / 2.0, transparentImage );
        hwRatio = ( double )transparentImage.height() / ( double )transparentImage.width();
      }
      else
      {
        p->drawImage( -img.width() / 2.0, -img.height() / 2.0, img );
        hwRatio = ( double )img.height() / ( double )img.width();
      }
    }
  }

  if ( usePict || !fitsInCache )
  {
    p->setOpacity( context.alpha() );
    const QPicture& pct = QgsSvgCache::instance()->svgAsPicture( path, size, fillColor, outlineColor, outlineWidth,
                          context.renderContext().scaleFactor(), context.renderContext().rasterScaleFactor(), context.renderContext().forceVectorOutput() );

    if ( pct.width() > 1 )
    {
      p->drawPicture( 0, 0, pct );
      hwRatio = ( double )pct.height() / ( double )pct.width();
    }
  }

  if ( context.selected() )
  {
    QPen pen( context.renderContext().selectionColor() );
    double penWidth = QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), QgsSymbolV2::MM );
    if ( penWidth > size / 20 )
    {
      // keep the pen width from covering symbol
      penWidth = size / 20;
    }
    double penOffset = penWidth / 2;
    pen.setWidth( penWidth );
    p->setPen( pen );
    p->setBrush( Qt::NoBrush );
    double wSize = size + penOffset;
    double hSize = size * hwRatio + penOffset;
    p->drawRect( QRectF( -wSize / 2.0, -hSize / 2.0, wSize, hSize ) );
  }

  p->restore();
}
Exemple #18
0
void QgsMapRenderer::render( QPainter* painter, double* forceWidthScale )
{
  //Lock render method for concurrent threads (e.g. from globe)
  QMutexLocker renderLock( &mRenderMutex );

  //flag to see if the render context has changed
  //since the last time we rendered. If it hasnt changed we can
  //take some shortcuts with rendering
  bool mySameAsLastFlag = true;

  QgsDebugMsg( "========== Rendering ==========" );

  if ( mExtent.isEmpty() )
  {
    QgsDebugMsg( "empty extent... not rendering" );
    return;
  }

  if ( mSize.width() == 1 && mSize.height() == 1 )
  {
    QgsDebugMsg( "size 1x1... not rendering" );
    return;
  }

  QPaintDevice* thePaintDevice = painter->device();
  if ( !thePaintDevice )
  {
    return;
  }

  // wait
  if ( mDrawing )
  {
    QgsDebugMsg( "already rendering" );
    QCoreApplication::processEvents();
  }

  if ( mDrawing )
  {
    QgsDebugMsg( "still rendering - skipping" );
    return;
  }

  mDrawing = true;

  QgsCoordinateTransform* ct;

#ifdef QGISDEBUG
  QgsDebugMsg( "Starting to render layer stack." );
  QTime renderTime;
  renderTime.start();
#endif

  if ( mOverview )
    mRenderContext.setDrawEditingInformation( !mOverview );

  mRenderContext.setPainter( painter );
  mRenderContext.setCoordinateTransform( 0 );
  //this flag is only for stopping during the current rendering progress,
  //so must be false at every new render operation
  mRenderContext.setRenderingStopped( false );

  //calculate scale factor
  //use the specified dpi and not those from the paint device
  //because sometimes QPainter units are in a local coord sys (e.g. in case of QGraphicsScene)
  double sceneDpi = mScaleCalculator->dpi();
  double scaleFactor = 1.0;
  if ( mOutputUnits == QgsMapRenderer::Millimeters )
  {
    if ( forceWidthScale )
    {
      scaleFactor = *forceWidthScale;
    }
    else
    {
      scaleFactor = sceneDpi / 25.4;
    }
  }
  double rasterScaleFactor = ( thePaintDevice->logicalDpiX() + thePaintDevice->logicalDpiY() ) / 2.0 / sceneDpi;
  if ( mRenderContext.rasterScaleFactor() != rasterScaleFactor )
  {
    mRenderContext.setRasterScaleFactor( rasterScaleFactor );
    mySameAsLastFlag = false;
  }
  if ( mRenderContext.scaleFactor() != scaleFactor )
  {
    mRenderContext.setScaleFactor( scaleFactor );
    mySameAsLastFlag = false;
  }
  if ( mRenderContext.rendererScale() != mScale )
  {
    //add map scale to render context
    mRenderContext.setRendererScale( mScale );
    mySameAsLastFlag = false;
  }
  if ( mLastExtent != mExtent )
  {
    mLastExtent = mExtent;
    mySameAsLastFlag = false;
  }

  mRenderContext.setLabelingEngine( mLabelingEngine );
  if ( mLabelingEngine )
    mLabelingEngine->init( this );

  // know we know if this render is just a repeat of the last time, we
  // can clear caches if it has changed
  if ( !mySameAsLastFlag )
  {
    //clear the cache pixmap if we changed resolution / extent
    QSettings mySettings;
    if ( mySettings.value( "/qgis/enable_render_caching", false ).toBool() )
    {
      QgsMapLayerRegistry::instance()->clearAllLayerCaches();
    }
  }

  QgsOverlayObjectPositionManager* overlayManager = overlayManagerFromSettings();
  QList<QgsVectorOverlay*> allOverlayList; //list of all overlays, used to draw them after layers have been rendered

  // render all layers in the stack, starting at the base
  QListIterator<QString> li( mLayerSet );
  li.toBack();

  QgsRectangle r1, r2;

  while ( li.hasPrevious() )
  {
    if ( mRenderContext.renderingStopped() )
    {
      break;
    }

    // Store the painter in case we need to swap it out for the
    // cache painter
    QPainter * mypContextPainter = mRenderContext.painter();

    QString layerId = li.previous();

    QgsDebugMsg( "Rendering at layer item " + layerId );

    // This call is supposed to cause the progress bar to
    // advance. However, it seems that updating the progress bar is
    // incompatible with having a QPainter active (the one that is
    // passed into this function), as Qt produces a number of errors
    // when try to do so. I'm (Gavin) not sure how to fix this, but
    // added these comments and debug statement to help others...
    QgsDebugMsg( "If there is a QPaintEngine error here, it is caused by an emit call" );

    //emit drawingProgress(myRenderCounter++, mLayerSet.size());
    QgsMapLayer *ml = QgsMapLayerRegistry::instance()->mapLayer( layerId );

    if ( !ml )
    {
      QgsDebugMsg( "Layer not found in registry!" );
      continue;
    }

    QgsDebugMsg( QString( "layer %1:  minscale:%2  maxscale:%3  scaledepvis:%4  extent:%5" )
                 .arg( ml->name() )
                 .arg( ml->minimumScale() )
                 .arg( ml->maximumScale() )
                 .arg( ml->hasScaleBasedVisibility() )
                 .arg( ml->extent().toString() )
               );

    if ( !ml->hasScaleBasedVisibility() || ( ml->minimumScale() < mScale && mScale < ml->maximumScale() ) || mOverview )
    {
      connect( ml, SIGNAL( drawingProgress( int, int ) ), this, SLOT( onDrawingProgress( int, int ) ) );

      //
      // Now do the call to the layer that actually does
      // the rendering work!
      //

      bool split = false;

      if ( hasCrsTransformEnabled() )
      {
        r1 = mExtent;
        split = splitLayersExtent( ml, r1, r2 );
        ct = new QgsCoordinateTransform( ml->crs(), *mDestCRS );
        mRenderContext.setExtent( r1 );
        QgsDebugMsg( "  extent 1: " + r1.toString() );
        QgsDebugMsg( "  extent 2: " + r2.toString() );
        if ( !r1.isFinite() || !r2.isFinite() ) //there was a problem transforming the extent. Skip the layer
        {
          continue;
        }
      }
      else
      {
        ct = NULL;
      }

      mRenderContext.setCoordinateTransform( ct );

      //decide if we have to scale the raster
      //this is necessary in case QGraphicsScene is used
      bool scaleRaster = false;
      QgsMapToPixel rasterMapToPixel;
      QgsMapToPixel bk_mapToPixel;

      if ( ml->type() == QgsMapLayer::RasterLayer && qAbs( rasterScaleFactor - 1.0 ) > 0.000001 )
      {
        scaleRaster = true;
      }


      //create overlay objects for features within the view extent
      if ( ml->type() == QgsMapLayer::VectorLayer && overlayManager )
      {
        QgsVectorLayer* vl = qobject_cast<QgsVectorLayer *>( ml );
        if ( vl )
        {
          QList<QgsVectorOverlay*> thisLayerOverlayList;
          vl->vectorOverlays( thisLayerOverlayList );

          QList<QgsVectorOverlay*>::iterator overlayIt = thisLayerOverlayList.begin();
          for ( ; overlayIt != thisLayerOverlayList.end(); ++overlayIt )
          {
            if (( *overlayIt )->displayFlag() )
            {
              ( *overlayIt )->createOverlayObjects( mRenderContext );
              allOverlayList.push_back( *overlayIt );
            }
          }

          overlayManager->addLayer( vl, thisLayerOverlayList );
        }
      }

      // Force render of layers that are being edited
      // or if there's a labeling engine that needs the layer to register features
      if ( ml->type() == QgsMapLayer::VectorLayer )
      {
        QgsVectorLayer* vl = qobject_cast<QgsVectorLayer *>( ml );
        if ( vl->isEditable() ||
             ( mRenderContext.labelingEngine() && mRenderContext.labelingEngine()->willUseLayer( vl ) ) )
        {
          ml->setCacheImage( 0 );
        }
      }

      QSettings mySettings;
      if ( ! split )//render caching does not yet cater for split extents
      {
        if ( mySettings.value( "/qgis/enable_render_caching", false ).toBool() )
        {
          if ( !mySameAsLastFlag || ml->cacheImage() == 0 )
          {
            QgsDebugMsg( "Caching enabled but layer redraw forced by extent change or empty cache" );
            QImage * mypImage = new QImage( mRenderContext.painter()->device()->width(),
                                            mRenderContext.painter()->device()->height(), QImage::Format_ARGB32 );
            mypImage->fill( 0 );
            ml->setCacheImage( mypImage ); //no need to delete the old one, maplayer does it for you
            QPainter * mypPainter = new QPainter( ml->cacheImage() );
            // Changed to enable anti aliasing by default in QGIS 1.7
            if ( mySettings.value( "/qgis/enable_anti_aliasing", true ).toBool() )
            {
              mypPainter->setRenderHint( QPainter::Antialiasing );
            }
            mRenderContext.setPainter( mypPainter );
          }
          else if ( mySameAsLastFlag )
          {
            //draw from cached image
            QgsDebugMsg( "Caching enabled --- drawing layer from cached image" );
            mypContextPainter->drawImage( 0, 0, *( ml->cacheImage() ) );
            disconnect( ml, SIGNAL( drawingProgress( int, int ) ), this, SLOT( onDrawingProgress( int, int ) ) );
            //short circuit as there is nothing else to do...
            continue;
          }
        }
      }

      if ( scaleRaster )
      {
        bk_mapToPixel = mRenderContext.mapToPixel();
        rasterMapToPixel = mRenderContext.mapToPixel();
        rasterMapToPixel.setMapUnitsPerPixel( mRenderContext.mapToPixel().mapUnitsPerPixel() / rasterScaleFactor );
        rasterMapToPixel.setYMaximum( mSize.height() * rasterScaleFactor );
        mRenderContext.setMapToPixel( rasterMapToPixel );
        mRenderContext.painter()->save();
        mRenderContext.painter()->scale( 1.0 / rasterScaleFactor, 1.0 / rasterScaleFactor );
      }


      if ( !ml->draw( mRenderContext ) )
      {
        emit drawError( ml );
      }
      else
      {
        QgsDebugMsg( "Layer rendered without issues" );
      }

      if ( split )
      {
        mRenderContext.setExtent( r2 );
        if ( !ml->draw( mRenderContext ) )
        {
          emit drawError( ml );
        }
      }

      if ( scaleRaster )
      {
        mRenderContext.setMapToPixel( bk_mapToPixel );
        mRenderContext.painter()->restore();
      }

      if ( mySettings.value( "/qgis/enable_render_caching", false ).toBool() )
      {
        if ( !split )
        {
          // composite the cached image into our view and then clean up from caching
          // by reinstating the painter as it was swapped out for caching renders
          delete mRenderContext.painter();
          mRenderContext.setPainter( mypContextPainter );
          //draw from cached image that we created further up
          mypContextPainter->drawImage( 0, 0, *( ml->cacheImage() ) );
        }
      }
      disconnect( ml, SIGNAL( drawingProgress( int, int ) ), this, SLOT( onDrawingProgress( int, int ) ) );
    }
    else // layer not visible due to scale
    {
Exemple #19
0
void TileView::render(QPainter& painter, const QRect& rect, int priority)
{
    // Hide tiles not yet revealed to player
    if (!m_mapView->activePlayer()->hasSeen(m_tile))
    {
        painter.fillRect(rect, QColor(64, 64, 64));
        return;
    }

    // Draw revealed tiles
    switch (priority)
    {
        case 0:
            // Display of stars can span multiple tiles, so must be drawn first
            if (m_tile->isStar())
            {
                drawImage(painter, rect);
            }
            break;

        case 1:
            // Draw planets, colonies, units, etc.
            if (m_tile->isPlanet())
            {
                drawImage(painter, rect);
            }

            if (m_tile->hasColony())
            {
                QColor colour = m_tile->colony()->player()->colour();
                colour.setAlpha(64);
                painter.fillRect(rect, colour);
            }

            // Draw units only if tile is currently visible
            if (m_tile->hasUnit() && m_mapView->activePlayer()->canSee(m_tile))
            {
                Unit* unit;

                if (m_tile->units().contains(m_mapView->activeUnit()))
                {
                    unit = m_mapView->activeUnit();
                }
                else
                {
                    unit = m_tile->units().first();
                }

                painter.drawImage(rect, unit->type()->image());
            }

            if (m_tile->isPlanet() && m_mapView->activePlayer()->canColonise(m_tile->planet()))
            {
                painter.fillRect(rect.right() - 8, rect.top(), 8, 8, Qt::yellow);
            }
            break;

        case 2:
            if (m_tile->hasColony())
            {
                painter.setPen(Qt::white);

                // Display colony name
                painter.drawText(
                   rect.x() - rect.width() * 2,
                   rect.y() + rect.height(),
                   rect.width() * 5,
                   rect.height() / 2,
                   Qt::AlignTop | Qt::AlignCenter,
                   m_tile->colony()->name()
                );

                // Display colony size
                painter.drawText(
                   rect,
                   Qt::AlignTop | Qt::AlignRight,
                   QString::number(m_tile->colony()->size())
                );
            }

            // If behind fog of war, make tile slightly faded
            if (!m_mapView->activePlayer()->canSee(m_tile))
            {
                painter.fillRect(rect, QColor(64, 64, 64, 128));
            }
            break;

        default:
            Q_ASSERT(false);
            break;
    }

}
Exemple #20
0
void KniftyClient::update_captionBuffer()
{
    if (!KniftyHandler::initialized()) return;

    const uint maxCaptionLength = 300; // truncate captions longer than this!
    QString captionText(caption() );
    if (captionText.length() > maxCaptionLength) {
        captionText.truncate(maxCaptionLength);
        captionText.append(" [...]");
    }

    QFontMetrics fm(s_titleFont);
    int captionWidth  = fm.width(captionText);

    QPixmap textPixmap;
    QPainter painter;
    if(KniftyHandler::titleShadow())
    {
        // prepare the shadow
        textPixmap = QPixmap(captionWidth+2*2, s_titleHeight ); // 2*2 px shadow space
        textPixmap.fill(QColor(0,0,0));
        textPixmap.setMask( textPixmap.createHeuristicMask(TRUE) );
        painter.begin(&textPixmap);
        painter.setFont(s_titleFont);
        painter.setPen(white);
        painter.drawText(textPixmap.rect(), AlignCenter, captionText );
        painter.end();
    }

    QImage shadow;
    ShadowEngine se;

    // active
    aCaptionBuffer->resize(captionWidth+4, s_titleHeight ); // 4 px shadow
    painter.begin(aCaptionBuffer);
    painter.drawTiledPixmap(aCaptionBuffer->rect(), *aTitleBarTile);
    if(KniftyHandler::titleShadow())
    {
        shadow = se.makeShadow(textPixmap, QColor(0, 0, 0));
        painter.drawImage(1, 1, shadow);
    }
    painter.setFont(s_titleFont);
    painter.setPen(options()->color(KDecoration::ColorFont, true));
    painter.drawText(aCaptionBuffer->rect(), AlignCenter, captionText );
    painter.end();


    // inactive
    iCaptionBuffer->resize(captionWidth+4, s_titleHeight );
    painter.begin(iCaptionBuffer);
    painter.drawTiledPixmap(iCaptionBuffer->rect(), *iTitleBarTile);
    if(KniftyHandler::titleShadow())
    {
        painter.drawImage(1, 1, shadow);
    }
    painter.setFont(s_titleFont);
    painter.setPen(options()->color(KDecoration::ColorFont, false));
    painter.drawText(iCaptionBuffer->rect(), AlignCenter, captionText );
    painter.end();

    captionBufferDirty = false;
}
QSizeF QgsSymbolV2LegendNode::drawSymbol( const QgsLegendSettings& settings, ItemContext* ctx, double itemHeight ) const
{
  QgsSymbolV2* s = mItem.symbol();
  if ( !s )
  {
    return QSizeF();
  }

  // setup temporary render context
  QgsRenderContext context;
  context.setScaleFactor( settings.dpi() / 25.4 );
  context.setRendererScale( settings.mapScale() );
  context.setMapToPixel( QgsMapToPixel( 1 / ( settings.mmPerMapUnit() * context.scaleFactor() ) ) ); // hope it's ok to leave out other params
  context.setForceVectorOutput( true );
  context.setPainter( ctx ? ctx->painter : 0 );

  //Consider symbol size for point markers
  double height = settings.symbolSize().height();
  double width = settings.symbolSize().width();
  double size = 0;
  //Center small marker symbols
  double widthOffset = 0;
  double heightOffset = 0;

  if ( QgsMarkerSymbolV2* markerSymbol = dynamic_cast<QgsMarkerSymbolV2*>( s ) )
  {
    // allow marker symbol to occupy bigger area if necessary
    size = markerSymbol->size() * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context, s->outputUnit(), s->mapUnitScale() ) / context.scaleFactor();
    height = size;
    width = size;
    if ( width < settings.symbolSize().width() )
    {
      widthOffset = ( settings.symbolSize().width() - width ) / 2.0;
    }
    if ( height < settings.symbolSize().height() )
    {
      heightOffset = ( settings.symbolSize().height() - height ) / 2.0;
    }
  }

  if ( ctx )
  {
    double currentXPosition = ctx->point.x();
    double currentYCoord = ctx->point.y() + ( itemHeight - settings.symbolSize().height() ) / 2;
    QPainter* p = ctx->painter;

    //setup painter scaling to dots so that raster symbology is drawn to scale
    double dotsPerMM = context.scaleFactor();

    int opacity = 255;
    if ( QgsVectorLayer* vectorLayer = dynamic_cast<QgsVectorLayer*>( layerNode()->layer() ) )
      opacity = 255 - ( 255 * vectorLayer->layerTransparency() / 100 );

    p->save();
    p->setRenderHint( QPainter::Antialiasing );
    p->translate( currentXPosition + widthOffset, currentYCoord + heightOffset );
    p->scale( 1.0 / dotsPerMM, 1.0 / dotsPerMM );
    if ( opacity != 255 && settings.useAdvancedEffects() )
    {
      //semi transparent layer, so need to draw symbol to an image (to flatten it first)
      //create image which is same size as legend rect, in case symbol bleeds outside its alloted space
      QSize tempImageSize( width * dotsPerMM, height * dotsPerMM );
      QImage tempImage = QImage( tempImageSize, QImage::Format_ARGB32 );
      tempImage.fill( Qt::transparent );
      QPainter imagePainter( &tempImage );
      context.setPainter( &imagePainter );
      s->drawPreviewIcon( &imagePainter, tempImageSize, &context );
      context.setPainter( ctx->painter );
      //reduce opacity of image
      imagePainter.setCompositionMode( QPainter::CompositionMode_DestinationIn );
      imagePainter.fillRect( tempImage.rect(), QColor( 0, 0, 0, opacity ) );
      imagePainter.end();
      //draw rendered symbol image
      p->drawImage( 0, 0, tempImage );
    }
    else
    {
      s->drawPreviewIcon( p, QSize( width * dotsPerMM, height * dotsPerMM ), &context );
    }
    p->restore();
  }

  return QSizeF( qMax( width + 2 * widthOffset, ( double ) settings.symbolSize().width() ),
                 qMax( height + 2 * heightOffset, ( double ) settings.symbolSize().height() ) );
}
Exemple #22
0
void ImageView::draw(QPainter& p, const QRectF& R, const QImage& image) {
    QRect aR = R.toAlignedRect();
    p.drawImage(aR.x(), aR.y(), image.copy(aR));
}
Exemple #23
0
void BitmapImage::paintImage(QPainter& painter)
{
    painter.drawImage(mBounds.topLeft(), *image());
}
QSizeF QgsSymbolLegendNode::drawSymbol( const QgsLegendSettings &settings, ItemContext *ctx, double itemHeight ) const
{
  QgsSymbol *s = mItem.symbol();
  if ( !s )
  {
    return QSizeF();
  }

  // setup temporary render context
  QgsRenderContext context;
  context.setScaleFactor( settings.dpi() / 25.4 );
  context.setRendererScale( settings.mapScale() );
  context.setMapToPixel( QgsMapToPixel( 1 / ( settings.mmPerMapUnit() * context.scaleFactor() ) ) );
  context.setForceVectorOutput( true );
  context.setPainter( ctx ? ctx->painter : nullptr );

  if ( ctx && ctx->context )
  {
    context.setExpressionContext( ctx->context->expressionContext() );
  }
  else
  {
    // setup a minimal expression context
    QgsExpressionContext expContext;
    expContext.appendScopes( QgsExpressionContextUtils::globalProjectLayerScopes( nullptr ) );
    context.setExpressionContext( expContext );
  }

  //Consider symbol size for point markers
  double height = settings.symbolSize().height();
  double width = settings.symbolSize().width();

  //Center small marker symbols
  double widthOffset = 0;
  double heightOffset = 0;

  if ( QgsMarkerSymbol *markerSymbol = dynamic_cast<QgsMarkerSymbol *>( s ) )
  {
    // allow marker symbol to occupy bigger area if necessary
    double size = markerSymbol->size( context ) / context.scaleFactor();
    height = size;
    width = size;
    if ( width < settings.symbolSize().width() )
    {
      widthOffset = ( settings.symbolSize().width() - width ) / 2.0;
    }
    if ( height < settings.symbolSize().height() )
    {
      heightOffset = ( settings.symbolSize().height() - height ) / 2.0;
    }
  }

  if ( ctx && ctx->painter )
  {
    double currentXPosition = ctx->point.x();
    double currentYCoord = ctx->point.y() + ( itemHeight - settings.symbolSize().height() ) / 2;
    QPainter *p = ctx->painter;

    //setup painter scaling to dots so that raster symbology is drawn to scale
    double dotsPerMM = context.scaleFactor();

    int opacity = 255;
    if ( QgsVectorLayer *vectorLayer = dynamic_cast<QgsVectorLayer *>( layerNode()->layer() ) )
      opacity = ( 255 * vectorLayer->opacity() );

    p->save();
    p->setRenderHint( QPainter::Antialiasing );
    p->translate( currentXPosition + widthOffset, currentYCoord + heightOffset );
    p->scale( 1.0 / dotsPerMM, 1.0 / dotsPerMM );
    if ( opacity != 255 && settings.useAdvancedEffects() )
    {
      //semi transparent layer, so need to draw symbol to an image (to flatten it first)
      //create image which is same size as legend rect, in case symbol bleeds outside its alloted space
      QSize tempImageSize( width * dotsPerMM, height * dotsPerMM );
      QImage tempImage = QImage( tempImageSize, QImage::Format_ARGB32 );
      tempImage.fill( Qt::transparent );
      QPainter imagePainter( &tempImage );
      context.setPainter( &imagePainter );
      s->drawPreviewIcon( &imagePainter, tempImageSize, &context );
      context.setPainter( ctx->painter );
      //reduce opacity of image
      imagePainter.setCompositionMode( QPainter::CompositionMode_DestinationIn );
      imagePainter.fillRect( tempImage.rect(), QColor( 0, 0, 0, opacity ) );
      imagePainter.end();
      //draw rendered symbol image
      p->drawImage( 0, 0, tempImage );
    }
    else
    {
      s->drawPreviewIcon( p, QSize( width * dotsPerMM, height * dotsPerMM ), &context );
    }

    if ( !mTextOnSymbolLabel.isEmpty() )
    {
      QFontMetricsF fm( mTextOnSymbolTextFormat.scaledFont( context ) );
      qreal yBaselineVCenter = ( height * dotsPerMM + fm.ascent() - fm.descent() ) / 2;
      QgsTextRenderer::drawText( QPointF( width * dotsPerMM / 2, yBaselineVCenter ), 0, QgsTextRenderer::AlignCenter,
                                 QStringList() << mTextOnSymbolLabel, context, mTextOnSymbolTextFormat );
    }

    p->restore();
  }

  return QSizeF( std::max( width + 2 * widthOffset, static_cast< double >( settings.symbolSize().width() ) ),
                 std::max( height + 2 * heightOffset, static_cast< double >( settings.symbolSize().height() ) ) );
}
Exemple #25
0
void ArthurFrame::paintEvent(QPaintEvent *e)
{
    static QImage *static_image = 0;
    QPainter painter;
    if (preferImage()
#ifdef QT_OPENGL_SUPPORT
        && !m_use_opengl
#endif
        ) {
        if (!static_image || static_image->size() != size()) {
            delete static_image;
            static_image = new QImage(size(), QImage::Format_RGB32);
        }
        painter.begin(static_image);

        int o = 10;

        QBrush bg = palette().brush(QPalette::Background);
        painter.fillRect(0, 0, o, o, bg);
        painter.fillRect(width() - o, 0, o, o, bg);
        painter.fillRect(0, height() - o, o, o, bg);
        painter.fillRect(width() - o, height() - o, o, o, bg);
    } else {
#ifdef QT_OPENGL_SUPPORT
        if (m_use_opengl) {
            painter.begin(glw);
            painter.fillRect(QRectF(0, 0, glw->width(), glw->height()), palette().color(backgroundRole()));
        } else {
            painter.begin(this);
        }
#else
        painter.begin(this);
#endif
    }

    painter.setClipRect(e->rect());

    painter.setRenderHint(QPainter::Antialiasing);

    QPainterPath clipPath;

    QRect r = rect();
    qreal left = r.x() + 1;
    qreal top = r.y() + 1;
    qreal right = r.right();
    qreal bottom = r.bottom();
    qreal radius2 = 8 * 2;

    clipPath.moveTo(right - radius2, top);
    clipPath.arcTo(right - radius2, top, radius2, radius2, 90, -90);
    clipPath.arcTo(right - radius2, bottom - radius2, radius2, radius2, 0, -90);
    clipPath.arcTo(left, bottom - radius2, radius2, radius2, 270, -90);
    clipPath.arcTo(left, top, radius2, radius2, 180, -90);
    clipPath.closeSubpath();

    painter.save();
    painter.setClipPath(clipPath, Qt::IntersectClip);

    painter.drawTiledPixmap(rect(), m_tile);

    // client painting

    paint(&painter);

    painter.restore();

    painter.save();
    if (m_show_doc)
        paintDescription(&painter);
    painter.restore();

    int level = 180;
    painter.setPen(QPen(QColor(level, level, level), 2));
    painter.setBrush(Qt::NoBrush);
    painter.drawPath(clipPath);

    if (preferImage()
#ifdef QT_OPENGL_SUPPORT
        && !m_use_opengl
#endif
        ) {
        painter.end();
        painter.begin(this);
        painter.drawImage(e->rect(), *static_image, e->rect());
    }

#ifdef QT_OPENGL_SUPPORT
    if (m_use_opengl && (inherits("PathDeformRenderer") || inherits("PathStrokeRenderer") || inherits("CompositionRenderer") || m_show_doc))
        glw->swapBuffers();
#endif
}
Exemple #26
0
void PrintLayout::printProfileDives(int divesPerRow, int divesPerColumn)
{
	int i, row = 0, col = 0, printed = 0, total = estimateTotalDives();
	int animationOriginal = prefs.animation_speed;

	struct dive *dive;
	if (!total)
		return;

	// disable animations on the profile:
	prefs.animation_speed = 0;

	// setup a painter
	QPainter painter;
	painter.begin(printer);
	painter.setRenderHint(QPainter::Antialiasing);
	painter.setRenderHint(QPainter::SmoothPixmapTransform);

	// setup the profile widget
	QPointer<ProfileWidget2> profile = MainWindow::instance()->graphics();
	const int profileFrameStyle = profile->frameStyle();
	profile->setFrameStyle(QFrame::NoFrame);
	profile->setPrintMode(true, !printOptions->color_selected);
	profile->setFontPrintScale(divesPerRow * divesPerColumn > 3 ? 0.6 : 1.0);
	QSize originalSize = profile->size();
	// swap rows/col for landscape
	if (printer->orientation() == QPrinter::Landscape) {
		int swap = divesPerColumn;
		divesPerColumn = divesPerRow;
		divesPerRow = swap;
	}

	// padding in pixels between two dives. no padding if only one dive per page.
	const int padDef = 20;
	const int padW = (divesPerColumn < 2) ? 0 : padDef;
	const int padH = (divesPerRow < 2) ? 0 : padDef;
	// estimate dimensions for a single dive
	const int scaledW = ESTIMATE_DIVE_DIM(pageW, divesPerColumn, padW);
	const int scaledH = ESTIMATE_DIVE_DIM(pageH, divesPerRow, padH);
	// padding in pixels between profile and table
	const int padPT = 5;
	// create a model and table
	ProfilePrintModel model;
	model.setFontsize(7); // if this is changed we also need to change 'const int sr' in the constructor
	// if there is only one dive per page row we pass fitNotesToHeight to be almost half the page height
	QPointer<QTableView> table(createProfileTable(&model, scaledW, (divesPerRow == 1) ? scaledH * 0.45 : 0.0));
	// profilePrintTableMaxH updates after the table is created
	const int tableH = profilePrintTableMaxH;
	// resize the profile widget
	profile->resize(scaledW, scaledH - tableH - padPT);
	// offset table or profile on top
	int yOffsetProfile = 0, yOffsetTable = 0;
	if (printOptions->notes_up)
		yOffsetProfile = tableH + padPT;
	else
		yOffsetTable = scaledH - tableH;

	// plot the dives at specific rows and columns on the page
	for_each_dive (i, dive) {
		if (!dive->selected && printOptions->print_selected)
			continue;
		if (col == divesPerColumn) {
			col = 0;
			row++;
			if (row == divesPerRow) {
				row = 0;
				printer->newPage();
			}
		}
		// draw a profile
		QTransform origTransform = painter.transform();
		painter.translate((scaledW + padW) * col, (scaledH + padH) * row + yOffsetProfile);
		profile->plotDive(dive, true); // make sure the profile is actually redrawn
#ifdef Q_OS_LINUX // on Linux there is a vector line bug (big lines in PDF), which forces us to render to QImage
		QImage image(scaledW, scaledH - tableH - padPT, QImage::Format_ARGB32);
		QPainter imgPainter(&image);
		imgPainter.setRenderHint(QPainter::Antialiasing);
		imgPainter.setRenderHint(QPainter::SmoothPixmapTransform);
		profile->render(&imgPainter, QRect(0, 0, scaledW, scaledH - tableH - padPT));
		imgPainter.end();
		painter.drawImage(image.rect(),image);
#else // for other OS we can try rendering the profile as vector
		profile->render(&painter, QRect(0, 0, scaledW, scaledH - tableH - padPT));
#endif
		painter.setTransform(origTransform);

		// draw a table
		QPicture pic;
		QPainter picPainter;
		painter.translate((scaledW + padW) * col, (scaledH + padH) * row + yOffsetTable);
		model.setDive(dive);
		picPainter.begin(&pic);
		table->render(&picPainter);
		picPainter.end();
		painter.drawPicture(QPoint(0,0), pic);
		painter.setTransform(origTransform);
		col++;
		printed++;
		emit signalProgress((printed * 100) / total);
	}
	// cleanup
	painter.end();
	profile->setFrameStyle(profileFrameStyle);
	profile->setPrintMode(false);
	profile->resize(originalSize);
	// we need to force a redraw of the profile so it switches back from print mode
	profile->plotDive(0, true);
	// re-enable animations
	prefs.animation_speed = animationOriginal;
}
Exemple #27
0
void ossimGui::ImageScrollWidget::paintMultiLayer(QPainter& painter)
{
   if(m_multiLayerAlgorithm != ANIMATION_ALGORITHM)
   {
      ossimRefPtr<Layer> topLayer    = m_layers->layer((ossim_uint32)0);
      ossimRefPtr<Layer> bottomLayer    = m_layers->layer((ossim_uint32)1);
      if(topLayer.valid()&&bottomLayer.valid())
      {
         ossimRefPtr<StaticTileImageCache> topTileCache = topLayer->tileCache();
         ossimRefPtr<StaticTileImageCache> bottomTileCache = bottomLayer->tileCache();
         
         if(topTileCache.valid()&&bottomTileCache.valid())
         {
            ossimIrect rect = topTileCache->getRect();
            QRectF rectF    = m_scrollToLocal.mapRect(QRectF(rect.ul().x, rect.ul().y, rect.width(), rect.height()));
            ossimIpt topOriginOffset = ossimDpt(rectF.x(), rectF.y());
            // for scrolling we need to offset from the tile location to the actual rect indicated by the viewport.
            // 
            ossim_uint32 w = rect.width();
            ossim_uint32 h = rect.height();
            switch(m_multiLayerAlgorithm)
            {
               case HORIZONTAL_SWIPE_ALGORITHM:
               {
                  ossim_int64 topLayerx     = topOriginOffset.x;
                  ossim_int64 bottomLayerx  = m_activePointEnd.x();
                  ossim_int64 topLayerWidth = bottomLayerx - topLayerx;
                  painter.drawImage(topLayerx, topOriginOffset.y, topTileCache->getCache(), 0,0,topLayerWidth,h);
                  painter.drawImage(topLayerx+topLayerWidth, topOriginOffset.y, bottomTileCache->getCache(), topLayerWidth, 0);
                  break;
               }
               case VERTICAL_SWIPE_ALGORITHM:
               {
                  ossim_int64 topLayery    = topOriginOffset.y;
                  ossim_int64 bottomLayery = m_activePointEnd.y();
                  ossim_int64 topLayerHeight = bottomLayery - topLayery;
                  painter.drawImage(topOriginOffset.x, topLayery, topTileCache->getCache(), 0, 0, w, topLayerHeight);
                  painter.drawImage(topOriginOffset.x, topLayery+topLayerHeight, bottomTileCache->getCache(), 0, topLayerHeight);
                  break;
               }
               case BOX_SWIPE_ALGORITHM:
               {
                  painter.drawImage(topOriginOffset.x, topOriginOffset.y, topTileCache->getCache());
                  ossim_int64 minx = ossim::min(m_activePointStart.x(), m_activePointEnd.x());
                  ossim_int64 maxx = ossim::max(m_activePointStart.x(), m_activePointEnd.x());
                  ossim_int64 miny = ossim::min(m_activePointStart.y(), m_activePointEnd.y());
                  ossim_int64 maxy = ossim::max(m_activePointStart.y(), m_activePointEnd.y());
                  ossim_int64 w = maxx-minx;
                  ossim_int64 h = maxy-miny;
                  ossim_int64 x = minx;
                  ossim_int64 y = miny;
                  QPointF scrollPoint = m_localToScroll.map(QPointF(x,y));
                  ossimDrect cacheRect = bottomTileCache->getRect();
                  ossimDpt delta = ossimDpt(scrollPoint.x(), scrollPoint.y()) - cacheRect.ul();
                  
                  painter.drawImage(x, y, bottomTileCache->getCache(), delta.x, delta.y, w, h);
                  break;
               }
               case CIRCLE_SWIPE_ALGORITHM:
               {
                  // QImage& cahceImage = topTileCache->getCache();
                  // draw top and then overlay the bottom
                  ossim_int64 minx = ossim::min(m_activePointStart.x(), m_activePointEnd.x());
                  ossim_int64 maxx = ossim::max(m_activePointStart.x(), m_activePointEnd.x());
                  ossim_int64 miny = ossim::min(m_activePointStart.y(), m_activePointEnd.y());
                  ossim_int64 maxy = ossim::max(m_activePointStart.y(), m_activePointEnd.y());
                  ossim_int64 w = maxx-minx;
                  ossim_int64 h = maxy-miny;
                  ossim_int64 x = minx;
                  ossim_int64 y = miny;

                  // QPointF scrollPoint = m_localToScroll.map(QPointF(x,y));
                  // ossimDpt cachePt = ossimDpt(scrollPoint.x(), scrollPoint.y()) - topTileCache->getRect().ul();
                  painter.save();
                  painter.drawImage(topOriginOffset.x, topOriginOffset.y, topTileCache->getCache());
                  painter.setBrush(QBrush(bottomTileCache->getCache()));
                  painter.setPen(Qt::NoPen);
                  
                  // this part is a little tricky but for the texturing to be placed in the ellipse properly
                  // I had to add a translation for the painter because the cache might extend past the current scroll region because it
                  // is on tile boundaries
                  //
                  // Because we shift for texturing with the QBrush we must undo the shift when drawing the ellipse so it lines up with
                  // the mouse draws.  The topOriginOffset holds the shift.
                  //
                  painter.translate(topOriginOffset.x, topOriginOffset.y);
                  painter.drawEllipse(x-topOriginOffset.x,y-topOriginOffset.y,w,h);
                  painter.restore();
                  break;
               }
               default:
               {
                  break;
               }
            }
         }
      }
   }
   else
   {
   }
   
}
Exemple #28
0
void TWorldDisplay::DrawPlanet(QPainter &painter, const NSpace::TPlanet& planet) {

    glLoadIdentity();

    float radius = planet.Radius * World->Scale;
    float x = planet.X * World->Scale + World->OffsetX;
    float y = planet.Y * World->Scale + World->OffsetY;
    QColor planetColor = Qt::gray;
    if (planet.PlayerId != -1) {
        planetColor = GetQColor(World->IdToPlayer[planet.PlayerId]->Color);
    }

    glTranslatef(x, y, 300);
    glScalef(radius, radius, radius);

    glRotatef(Ang, 0, 1, 0);
    glRotatef(15, 1, 0, 0);

    const TPlanetGraphics& planetGraphics = GraphicManager.GetImage(planet.Type, radius * 10, planetColor);

    glBindTexture(GL_TEXTURE_2D, planetGraphics.TextureId);
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    glEnable(GL_TEXTURE_2D);
    if (radius > 20) {
        Sphere.draw();
    } else {
        LittleSphere.draw();
    }
    glDisable(GL_TEXTURE_2D);


    QPen pen(planetColor);
    pen.setWidth(2);

    QString energyString = QString("%1").arg(planet.Energy);
    QFontMetrics fm(painter.font());
    int textHeight = fm.height();
    int textWidth = fm.width(energyString);
    if (planet.Energy != -1 &&
       (planet.PlayerId == -1 ||
        planet.PlayerId == World->SelfId))
    {
        const QImage& fontBackground = GraphicManager.GetFontBackground(World->Scale);
        painter.drawImage(x - fontBackground.width() / 2, y - textHeight + textHeight / 3, fontBackground);
        pen.setColor(Qt::white);
        painter.setPen(pen);
        painter.drawText(x - textWidth / 2, y + textHeight / 3, energyString);
    }

    if (planet.PlayerId == World->SelfId &&
        World->SelectedPlanets.find(planet.ID) != World->SelectedPlanets.end())
    {
        pen.setColor(planetColor);
        painter.setPen(pen);
        painter.drawEllipse(x - radius - 4, y - radius - 4, radius * 2 + 8, radius * 2 + 8);
    } else if (World->SelectedTarget.is_initialized() &&
               planet.ID == *World->SelectedTarget)
    {
        NSpace::TPlayer* selfPlayer = World->SelfPlayer();
        if (selfPlayer != nullptr) {
            planetColor = GetQColor(selfPlayer->Color);
            pen.setColor(planetColor);
            painter.setPen(pen);
            painter.drawEllipse(x - radius - 4, y - radius - 4, radius * 2 + 8, radius * 2 + 8);
        }
    }
}
void QgsLayoutItem3DMap::draw( QgsLayoutItemRenderContext &context )
{
  QgsRenderContext &ctx = context.renderContext();
  QPainter *painter = ctx.painter();

  int w = static_cast<int>( std::ceil( rect().width() * ctx.scaleFactor() ) );
  int h = static_cast<int>( std::ceil( rect().height() * ctx.scaleFactor() ) );
  QRect r( 0, 0, w, h );

  painter->save();

  if ( !mSettings )
  {
    painter->drawText( r, Qt::AlignCenter, tr( "Scene not set" ) );
    painter->restore();
    return;
  }

  if ( mSettings->backgroundColor() != backgroundColor() )
  {
    mSettings->setBackgroundColor( backgroundColor() );
    mCapturedImage = QImage();
  }

  if ( !mCapturedImage.isNull() )
  {
    painter->drawImage( r, mCapturedImage );
    painter->restore();
    return;
  }

  // we do not have a cached image of the rendered scene - let's request one from the engine

  if ( mLayout->renderContext().isPreviewRender() )
  {
    painter->drawText( r, Qt::AlignCenter, tr( "Loading" ) );
    painter->restore();
  }

  QSizeF sizePixels = mLayout->renderContext().measurementConverter().convert( sizeWithUnits(), QgsUnitTypes::LayoutPixels ).toQSizeF();
  QSize sizePixelsInt = QSize( static_cast<int>( std::ceil( sizePixels.width() ) ),
                               static_cast<int>( std::ceil( sizePixels.height() ) ) );

  if ( !mEngine )
  {
    mEngine.reset( new QgsOffscreen3DEngine );
    connect( mEngine.get(), &QgsAbstract3DEngine::imageCaptured, this, &QgsLayoutItem3DMap::onImageCaptured );

    mEngine->setSize( sizePixelsInt );

    mScene = new Qgs3DMapScene( *mSettings, mEngine.get() );
    connect( mScene, &Qgs3DMapScene::sceneStateChanged, this, &QgsLayoutItem3DMap::onSceneStateChanged );

    mEngine->setRootEntity( mScene );
  }

  if ( mEngine->size() != sizePixelsInt )
    mEngine->setSize( sizePixelsInt );

  mScene->cameraController()->setCameraPose( mCameraPose );

  if ( mLayout->renderContext().isPreviewRender() )
  {
    onSceneStateChanged();
  }
  else
  {
    // we can't just request a capture and hope it will arrive at some point later.
    // this is not a preview, we need the rendered scene now!
    if ( mDrawing )
      return;
    mDrawing = true;
    Qgs3DUtils::captureSceneImage( *mEngine.get(), mScene );
    QImage img = Qgs3DUtils::captureSceneImage( *mEngine.get(), mScene );
    painter->drawImage( r, img );
    painter->restore();
    mDrawing = false;
  }
}
void GameCanvas::paintEvent(QPaintEvent *)
{
    QPainter app_painter(this);
    QPainter *painter;

    // check if cache is available
    if (this->is_cache_available) {
        // initialize painter
        painter = &app_painter;
        painter->setRenderHint(QPainter::Antialiasing);

        painter->drawImage(0, 0, drawing_cache.toImage());
    } else {
        // clean the cache
        this->drawing_cache = QPixmap(640,480);

        // make new painter
        painter = new QPainter(&drawing_cache);
        painter->setRenderHint(QPainter::Antialiasing);
    }

    // pointers for animation
    QPixmap *av = &assets["pc_av_01"];
    QPixmap *big_av = &assets["pc_big_av_01"];
    QPixmap *broken = &assets["pc_broken_01"];
    QPixmap *fixed = &assets["pc_fixed_01"];
    QPixmap *fixed_alt = &assets["pc_fixed_02"];

    // draw background
    if (!this->is_cache_available)
        for (int y=0; y<49; y++)
            for (int x=0; x<80; x++)
                painter->drawImage(x*8, y*8, assets["background"].toImage());

    // animate map
    switch (this->current_frame) {
    case 1:
        broken = &assets["pc_broken_02"];
        fixed = &assets["pc_fixed_02"];
        av = &assets["pc_av_02"];
        big_av = &assets["pc_big_av_02"];
        break;
    case 2:
        fixed_alt = &assets["pc_working_03"];
        break;
    case 3:
        broken = &assets["pc_broken_02"];
        fixed = &assets["pc_fixed_02"];
        av = &assets["pc_av_02"];
        big_av = &assets["pc_big_av_02"];
        break;
    default: break;
    }

    // render map
    for (int y=0; y<49; y++)
        for (int x=0; x<80; x++) {
            switch (app->map[x][y]) {
                case '#':
                    if (!this->is_cache_available)
                        painter->drawImage(x*8, y*8, assets["obstacle"].toImage());
                    break;
                case '@':
                    if (this->is_cache_available)
                        painter->drawImage(x*8, y*8, assets["doors"].toImage());
                    break;
                case '_':
                    if (this->is_cache_available)
                        painter->drawImage(x*8, y*8, assets["force_field"].toImage());
                    break;
                case '"':
                    if (!this->is_cache_available)
                        painter->drawImage(x*8, y*8, assets["sky"].toImage());
                    break;
                case '1':
                    if (!this->is_cache_available)
                        painter->drawImage(x*8, (y-1)*8, assets["pc"].toImage());
                    else
                        painter->drawImage(x*8, (y-1)*8, broken->toImage());
                    break;
                case '2':
                    if (!this->is_cache_available)
                        painter->drawImage(x*8, (y-1)*8, assets["pc"].toImage());
                    else
                        painter->drawImage(x*8, (y-1)*8, av->toImage());
                    break;
                case '3':
                    if (!this->is_cache_available)
                        painter->drawImage(x*8, (y-1)*8, assets["pc"].toImage());
                    else
                        painter->drawImage(x*8, (y-1)*8, fixed->toImage());
                    break;
                case '4':
                    if (!this->is_cache_available)
                        painter->drawImage(x*8, (y-1)*8, assets["pc"].toImage());
                    else
                        painter->drawImage(x*8, (y-1)*8, fixed_alt->toImage());
                    break;
                case '5':
                    if (!this->is_cache_available)
                        painter->drawImage(x*8, (y-1)*8, assets["pc"].toImage());
                    else
                        painter->drawImage(x*8, (y-1)*8, assets["pc_apple"].toImage());
                    break;
                case '6':
                    if (!this->is_cache_available)
                        painter->drawImage(x*8, (y-1)*8, assets["pc"].toImage());
                    else
                        if (current_frame == 2)
                            painter->drawImage(x*8, (y-1)*8, assets["pc_net5"].toImage());
                        else
                            painter->drawImage(x*8, (y-1)*8, fixed->toImage());
                    break;
                case '8':
                    if (!this->is_cache_available)
                        painter->drawImage(x*8, (y-1)*8, assets["big_pc"].toImage());
                    else
                        painter->drawImage(x*8, (y-1)*8, assets["pc_big_corrupted"].toImage());
                    break;
                case '9':
                    if (!this->is_cache_available)
                        painter->drawImage(x*8, (y-1)*8, assets["big_pc"].toImage());
                    else
                        painter->drawImage(x*8, (y-1)*8, big_av->toImage());
                    break;
                case '0':
                    if (!this->is_cache_available)
                        painter->drawImage(x*8, (y-1)*8, assets["pc"].toImage());
                    else
                        painter->drawImage(x*8, (y-1)*8, assets["pc_bsod"].toImage());
                    break;
            }
        }

    // draw all the people
    if (!this->is_cache_available)
        for (int i=0; i<people.count(); i++) {
            Person person = people.at(i);
            painter->drawImage(person.x*8, person.y*8, assets[person.gfx].toImage());
        }

    // draw player
    if (this->is_cache_available)
        painter->drawImage(app->player.x*8, app->player.y*8, assets[app->player.gfx].toImage());

    // draw UI
    if (this->is_cache_available)
        painter->drawImage(0, 0, assets["ui"].toImage());

    if (current_frame == 2)
        if (this->is_cache_available) painter->drawImage(app->story_pointer.x*8, app->story_pointer.y*8, assets["arrow"].toImage());

    //emit update_debuglabel("x: "+QString::number(app->player.x)+"  y: "+QString::number(app->player.y));

    if (!this->is_cache_available) {
        this->is_cache_available = true;
        //this->repaint();
    }
}