Move / Rotate Qt Image

I just want to move the image along the widget's axes and rotate around the center of the widget (for example, the canvas in any digital painting software), but it rotates around its upper left point ...

QPainter p(this); QTransform trans; trans.translate(width()/2, -height()/2); trans.rotate(angle); QTransform inverse = trans.inverted(); inverse.translate(-canvas.width()/2, -canvas.height()/2); p.setTransform(trans); p.drawImage(inverse.map(canvasPos), canvas); 

How to make it spin correctly?

+2
source share
2 answers

You can combine the initial re-placement of the image, rotation and centering of the final result in the center of the widget in one transformation.

The operations in QTransform are performed in the reverse order, because the last one applied to QTransform will be the first one applied to the image:

 // QImage canvas; QPainter p(this); QTransform trans; // Move to the center of the widget trans.translate(width()/2, height()/2); // Do the rotation trans.rotate(angle); // Move to the center of the image trans.translate(-canvas.width()/2, -canvas.height()/2); p.setTransform(trans); // Draw the image at (0,0), because everything is already handled by the transformation p.drawImage(QPoint(0,0), canvas); 
+4
source

The usual reason an object rotates around its upper left point, and not its center, is because it has its dimensions defined with 0.0 in the upper left corner, and not located in the center of the object.

You did not specify what the canvas object is, so assuming it is something like a QGraphicsRectItem, you will need to declare its top left, width, height as -x / 2, -y / 2, width, height, so that the center point the object was equal to 0.0. Then, when you rotate the object, it will rotate around its center.

In addition, you should try to separate the rotation and translation logic from the drawing functions for optimal performance.

+2
source

Source: https://habr.com/ru/post/1487793/


All Articles