围绕任意点旋转QPixmap

时间:2014-03-12 21:03:59

标签: c++ image qt user-interface

我试图做一个围绕任意点旋转图像的事情(通常在图像本身的边界内),但我想保留与未转换图像相对应的点。原点。

到目前为止,我使用QTransform方法旋转图像:

Qt代码:

image.transformed(QTransform()
                          .translate(-point.x(), -point.y())
                          .rotateRadians(rot)
                          .translate(point.x(), point.y()));

这将返回一个"旋转"围绕该点,但它被绘制成一个新的图像对象,其原点分别对应于变换后的图像,而不是原始图像,因此绘制图像使其具有正确的角度,但在某处偏离位置。有没有办法让A]计算原始原点在变换图像中的位置,或者B]旋转图像而不改变它的原点?​​

这是实践中的计划:

没有任何轮换:

Without Rotation

使用旋转(图像以新框的左上角为原点绘制,而不是图像的预转换原点):

With Rotation

1 个答案:

答案 0 :(得分:-1)

好吧,我提出的解决方案是,为了找到原始图像和旋转图像的偏移量,我找到两个图像的中心点并计算该偏移量,然后将其与旋转点一起使用作为绘画时绘制图像的位置。

QPixmap ImageBone::getTransformedImage(QPointF point, qreal rot, QPointF &origin, QPointF anchor = QPointF(0, 0))
{
    QPointF center = QPointF(image.width() / 2, image.height() / 2);
    qreal dist = QLineF(anchor, center).length();
    qreal a = qAtan2(anchor.y() - center.y(), anchor.x() - center.x());
    QPointF rotAnchor(qCos(rot + a) * dist, qSin(rot + a) * dist);
    rotAnchor += center;

    QPixmap rotImage = image.transformed(QTransform()
                                  .translate(-point.x(), -point.y())
                                  .rotateRadians(rot)
                                  .translate(point.x(), point.y())
                                 );

    QPointF rotCenter = QPointF(rotImage.width() / 2, rotImage.height() / 2);
    QPointF offset = rotCenter - center;

    origin = point - (rotAnchor + offset);

    return rotImage;
}
相关问题