Qt的分数像素大小

Fractional pixel size with Qt

本文关键字:像素 Qt      更新时间:2023-10-16

我想显示缩放后的图像,每个像素都有文本和图形注释。下面是一个示例程序,用它的值来注释灰度图像的每个像素:

int main(int argc, char *argv[])
{
    const int scale = 44;
    QApplication   a(argc, argv);
    QGraphicsScene scene;
    QGraphicsView  view(&scene);
    QImage         image("test.bmp");
    scene.addPixmap(QPixmap::fromImage(image.scaled(scale*image.width(), scale*image.height())));
    for (int x = 0; x < image.width(); ++x)
      for (int y = 0; y < image.height(); ++y) {
        auto text = new QGraphicsSimpleTextItem();
        text->setText(QString::number(qGray(image.pixel(x, y))));
        text->setBrush(QBrush(Qt::red));
        text->setPos(scale*(x+0.2), scale*(y+0.2));
        scene.addItem(text);
      }
    view.show();
    return a.exec();
}

它将图像像素重新缩放为scale x scale的正方形,并要求相应地重新缩放注释的坐标。我想保留1x1像素大小,并使用此坐标系进行注释:text->setPos(x+0.2, y+0.2)将替换上面的相应行。可以用QGraphicsScene完成吗?

QGraphicsView有自己的缩放比例,请使用它,而不是自己重新缩放图像。如果在将图像添加到场景之前缩放图像,则像素位置和像素数当然会发生更改。更简单的方法是使用QGraphicsView比例并保持原始图像的大小和像素位置。用于QGraphicsItem的位置也与图像中的位置相同。

对于文本,您可以设置一个标志:

text->setFlag(QGraphicsItem::ItemIgnoresTransformations,true);

无论你放大多少,都可以让它保持不变。

这应该有效:

const int scale = 44;
QApplication   a(argc, argv);
QGraphicsScene scene;
QGraphicsView  view(&scene);
QImage         image("test.bmp");
scene.addPixmap(QPixmap::fromImage(image));
for (int x = 0; x < image.width(); ++x) {
    for (int y = 0; y < image.height(); ++y) {
        QGraphicsSimpleTextItem* text = new QGraphicsSimpleTextItem();
        text->setText(QString::number(qGray(image.pixel(x, y))));
        text->setBrush(QBrush(Qt::red));
        text->setFlag(QGraphicsItem::ItemIgnoresTransformations,true);
        text->setPos(x+0.2, y+0.2);
        scene.addItem(text);
    }
}
view.scale(scale, scale);
view.show();
return a.exec();