旋转图像会导致Qt失真

时间:2012-10-10 19:24:48

标签: c++ qt image-rotation rounding-error

我在Qt中旋转图像时遇到了一些问题。每次用QPainter旋转图像时,它都会变得越来越扭曲。这是初始图片:

http://imageshack.us/photo/my-images/838/ship1.png/

经过一些迭代后,它变为:

http://imageshack.us/photo/my-images/11/ship2e.png/

这是我的代码:

void Ship::Move(int x, int y)
{
    QPixmap rotatePixmap(shipPixels.size());
    rotatePixmap.fill(Qt::transparent);

    QTransform transform;
    transform.translate(
            rotatePixmap.size().width() / 2,
            rotatePixmap.size().height() / 2
    );

    transform.rotate(degree);
    transform.translate(
            - rotatePixmap.size().width() / 2, 
            - rotatePixmap.size().height() / 2
    );

    QPainter p(&rotatePixmap);
    p.setRenderHints(
            QPainter::Antialiasing | QPainter::SmoothPixmapTransform,
            true
    );

    p.setTransform(transform);
    p.drawPixmap(0, 0, shipPixels);
    p.end();

    shipPixels = rotatePixmap;
    this->setPixmap(shipPixels);
    this->move(QPoint(x, y));
    degree = 0;
}

对我来说Qt保留了图像质量。这种行为很奇怪。有原因吗?

2 个答案:

答案 0 :(得分:1)

根据答案,新代码就是这样。发现自己有同样问题的其他用户可以获得此代码:

void Ship::Move(int x, int y)
{
    QPixmap sourceImage(shipPixels);

    QPixmap rotatePixmap(sourceImage.size());
    rotatePixmap.fill(Qt::transparent);

    QTransform transform;
    transform.translate(sourceImage.size().width() / 2, sourceImage.size().height() / 2);
    transform.rotate(degree);
    transform.translate(-sourceImage.size().width() / 2, -sourceImage.size().height() / 2);

    QPainter p;
    p.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform, true);
    p.begin(&rotatePixmap);
    p.setTransform(transform);
    p.drawPixmap(0, 0, sourceImage);
    p.end();

    rotatePixmap.save("temp.png");

    this->setPixmap(rotatePixmap);
    this->move(QPoint(x, y));
}

答案 1 :(得分:-3)

QPainter pixmap;
pixmap.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform,true);

这就是你要找的东西。