1。目标
我的同事和我一直试图在Qt中渲染旋转的椭圆体。正如我们所理解的那样,典型的解决方案方法包括将椭圆体的中心移动到坐标系的原点,在那里进行旋转,然后向后移动: http://qt-project.org/doc/qt-4.8/qml-rotation.html
2。示例代码
根据上面链接中列出的解决方案,我们提出了以下示例代码:
// Constructs and destructors
RIEllipse(QRect rect, RIShape* parent, bool isFilled = false)
: RIShape(parent, isFilled), _rect(rect), _angle(30)
{}
// Main functionality
virtual Status draw(QPainter& painter)
{
const QPen& prevPen = painter.pen();
painter.setPen(getContColor());
const QBrush& prevBrush = painter.brush();
painter.setBrush(getFillBrush(Qt::SolidPattern));
// Get rectangle center
QPoint center = _rect.center();
// Center the ellipse at the origin (0,0)
painter.translate(-center.x(), -center.y());
// Rotate the ellipse around its center
painter.rotate(_angle);
// Move the rotated ellipse back to its initial location
painter.translate(center.x(), center.y());
// Draw the ellipse rotated around its center
painter.drawEllipse(_rect);
painter.setBrush(prevBrush);
painter.setPen(prevPen);
return IL_SUCCESS;
}
如您所见,我们已在此测试样本中将旋转角度硬编码为30度。
第3。观测
椭圆出现在错误的位置,通常在画布区域之外。
4。问题
上面的示例代码有什么问题?
致以最诚挚的问候,
博德
P.S。提前感谢任何建设性的回应?
P.P.S。在发布此消息之前,我们在stackoverflow.com上搜索了相当多的内容。 Qt image move/rotation似乎反映了与上述链接类似的解决方案。
答案 0 :(得分:0)
在painter.translate(center.x(), center.y());
中,您将对象移动当前坐标的数量,从而使(2*center.x(), 2*center.y())
成为结果。您可能需要:
painter.translate(- center.x(), - center.y());
答案 1 :(得分:0)
将物体移回原点,旋转然后更换物体位置的理论是正确的。但是,您提供的代码根本不是翻译和旋转对象,而是翻译和旋转画家。在您referred to的示例问题中,他们想要围绕一个对象旋转整个图像,这就是为什么他们在旋转之前将画家移动到对象的中心。
对GraphicsItem进行旋转的最简单方法是初始定义项目,其中心位于对象的中心,而不是左上角。这样,任何旋转都将自动围绕对象中心,而无需翻译对象。
要做到这一点,你要定义带有x,y,宽度,高度的边界矩形的项目(-width / 2,-height / 2,width,height)。
或者,假设您的项目是从QGraphicsItem或QGraphicsObject继承的,您可以在旋转之前使用函数setTransformOriginPoint。