围绕矩形中心旋转

7

我需要将一个矩形绕其中心点旋转,并在QWidget的中心显示它。你能完成这个特定代码吗?如果可能的话,能否简化解释或提供最简单的解释链接?

请注意:我已经阅读了Qt文档,编译了处理旋转的示例/演示文稿,但我仍然无法理解它!

void Canvas::paintEvent(QPaintEvent *event)
{
    QPainter paint(this);

    paint.setBrush(Qt::transparent);
    paint.setPen(Qt::black);
    paint.drawLine(this->width()/2, 0, this->width()/2, this->height());
    paint.drawLine(0, this->height()/2, this->width(), this->height()/2);

    paint.setBrush(Qt::white);
    paint.setPen(Qt::blue);

    // Draw a 13x17 rectangle rotated to 45 degrees around its center-point
    // in the center of the canvas.

    paint.drawRect(QRect(0,0, 13, 17));

}
2个回答

14
 void paintEvent(QPaintEvent* event){
    QPainter painter(this);

    // xc and yc are the center of the widget's rect.
    qreal xc = width() * 0.5;
    qreal yc = height() * 0.5;

    painter.setPen(Qt::black);

    // draw the cross lines.
    painter.drawLine(xc, rect().top(), xc, rect().bottom());
    painter.drawLine(rect().left(), yc, rect().right(), yc);

    painter.setBrush(Qt::white);
    painter.setPen(Qt::blue);

    // Draw a 13x17 rectangle rotated to 45 degrees around its center-point
    // in the center of the canvas.

    // translates the coordinate system by xc and yc
    painter.translate(xc, yc);

    // then rotate the coordinate system by 45 degrees
    painter.rotate(45);

    // we need to move the rectangle that we draw by rx and ry so it's in the center.
    qreal rx = -(13 * 0.5);
    qreal ry = -(17 * 0.5);
    painter.drawRect(QRect(rx, ry, 13, 17));
  }

您现在处于绘图坐标系中。当您调用drawRect(x, y, 13, 17)时,其左上角位于坐标点(x,y)。如果要使(x,y)成为矩形的中心,则需要将矩形移动一半,即使用rxry

您可以通过调用resetTransform()来重置由translate()rotate()进行的转换。


4
认为现在我明白了正在发生的事情。无论如何,Painter始终从0,0开始。因此,当你将其平移至100,100时,Painter仍然从0,0开始,但新的0,0恰好位于100,100? - user336063

5

简单:

void rotate(QPainter* p, const QRectF& r, qreal angle, bool clock_wise) {
    p->translate(r.center());
    p->rotate(clock_wise ? angle : -angle);
    p->translate(-r.center());
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接