2013-05-16 133 views
2

我只是想移动图像的小部件的轴,并围绕小部件的中心(如任何数字绘画软件中的画布)旋转,但它围绕其左上角旋转...Qt图像移动/旋转

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); 

如何让它正确旋转?

回答

2

对象围绕其左上角而不是其中心旋转的常见原因是因为它的尺寸在左上角用0,0定义,而不是在对象的中心。你没有展示'canvas'对象是什么,所以假设它像QGraphicsRectItem,你需要声明它的左上角,宽度,高度为-x/2,-y/2,width ,高度以确保物体的中心点位于0,0。然后当你旋转物体时,它会围绕它的中心旋转。

此外,您应该尝试从绘画功能中分离旋转和平移逻辑以获得最佳性能。

4

您可以在单个转换中合并图像的初始重新缩放,旋转和最终结果在小部件中心的居中。

QTransform的操作被以相反的顺序进行,因为最新的一个施加到QTransform将施加到图像的第一个:

// 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);