Search code examples
c++qtqpainter

Drawing specified part of QPainterPath on QImage [zoom and pan]


i.e. if I specify some cubic lines from example specified in Qt5 tutorial:

QPainterPath path;
path.addRect(20, 20, 60, 60);

path.moveTo(0, 0);
path.cubicTo(99, 0,  50, 50,  99, 99);
path.cubicTo(0, 99,  50, 50,  0, 0);

QPainter painter(this);
painter.fillRect(0, 0, 100, 100, Qt::white);
painter.setPen(QPen(QColor(79, 106, 25), 1, Qt::SolidLine,
                    Qt::FlatCap, Qt::MiterJoin));
painter.setBrush(QColor(122, 163, 39));

painter.drawPath(path);

which constructs this set of curvesenter image description here

Now I'd like to render only a part of those curves on QImage specified by some region with starting point=[20px,50px] with width=80px and height=50px so resulting would look like this:enter image description here

Or if it is possible, to render with 3x zoom, so resulting QImage would look the same but had size=[240px,150px]

I am new to Qt, so could someone please showed me a working code example?


Solution

  • You can transform the painter coordinate system:

        QPainter painter(this);
        painter.scale(3, 3); // zoom 3 times
        painter.translate(-20, -50); // offset origin to 20x50
        // ... render stuff
    

    This has an advantage over the other answer, because it will be rendered as if you provided larger coordinates, instead of rendering it small and then enlarging the raster image, which will degrade image quality. Also, it is possible that Qt will optimize it to not render outside of the image, so it will render less, and you don't need to crop and throw results away.

    Result:

    enter image description here

    Compare that to an upscaled raster:

    enter image description here