Rotate QGraphicsPixmapItem results in shear if resizing without keeping aspect ratio

落花浮王杯 提交于 2019-12-13 02:00:23

问题


I am trying to rotate a QGraphicsPixmapItem child. For other QGraphicsItem, rotation and scaling work fine. But for a QGraphicsPixmapItem, if the size does not keep aspect ratio, instead of rotation I get shear.

sample code:

#include <QApplication>
#include <QGraphicsView>
#include <QMessageBox>
#include <QGraphicsPixmapItem>
#include <QFileDialog>

int main(int argc, char *argv[])
{
    QGraphicsScene s;
    s.setSceneRect(-200, -200, 500, 500);
    QGraphicsView view(&s);
    view.show();

    QGraphicsPixmapItem p;
    QString fileName = QFileDialog::getOpenFileName(0, QObject::tr("Open Image File"), QString(), QObject::tr("Png files (*.png);;Jpeg files (*.jpg *.jpeg);;Bitmap files (*.bmp)"));
    p.setPixmap(QPixmap(fileName));
    s.addItem(&p);
    QMessageBox::information(0, "", "");

    QTransform original = p.transform();

    // scale aspect ratio then rotate
    QTransform scalingTransform0(0.5, 0, 0, 0, 0.5, 0, 0, 0, 1);
    // p.setTransformOriginPoint(p.boundingRect().center()); // doesn't help shear
    p.setTransform(scalingTransform0 * original);
    p.setRotation(20);
    QMessageBox::information(0, "", "");

    // scale
    QTransform scalingTransform(0.5, 0, 0, 0, 1, 0, 0, 0, 1);
    p.setTransform(scalingTransform * original);
    QMessageBox::information(0, "", "");

    // rotate
    p.setRotation(20);
    QMessageBox::information(0, "", "");

    // unrotate then rotate again
    p.setRotation(0);
    QMessageBox::information(0, "", "");
    QTransform rotTransform = p.transform().rotate(20);
    p.setTransform(rotTransform);

    // or p.rotate(20);
    return app.exec();
}

Result:

I don't know how to get simple rotation, without shearing, for QGraphicsPixmapItems, and the item must remember the rotation.


回答1:


It is still a mystery why QGraphicsPixmapItem behaves so inconsistently.

A solution:
When scaling the item, scale the pixmap, apply resulting pixmap to item.
In that case rotation will work (because QGraphicsPixmapItem is not really scaled).

QPixmap p1 = pixmap.scaled(100, 100, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
p.setPixmap(p1);
p.setRotation(20);

This approach loses quality, so I ended up reloading the file

QPixmap p1 = (QPixmap(fileName)).scaled(100, 100, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
p.setPixmap(p1);
p.setRotation(20);

If there is a better solution, I will be happy to see it.



来源:https://stackoverflow.com/questions/31844152/rotate-qgraphicspixmapitem-results-in-shear-if-resizing-without-keeping-aspect-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!