c++ - Qt 的小数像素大小

标签 c++ qt graphics

我想显示带有每个像素的文本和图形注释的缩放图像。这是一个用其值注释灰度图像的每个像素的示例程序:

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();
}

它将图像像素重新缩放为 scalexscale 正方形,并需要相应的坐标重新缩放以进行注释。我想保留 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();

关于c++ - Qt 的小数像素大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32496240/

相关文章:

C++ 转义字符串中出现的\

qt - 如何使用 Qtranslator 翻译在 Qapp 中动态添加的字符串?

c++ - 推导多个参数包

c++ - 如何解决 OpenGL/GLSL 上的观察矩阵问题

math - 如何在平面上随机但均匀地分布节点

c++ - screen.h头文件方法困惑

c++ - C++ 中的空指针

c++ - std::make_unique 和 std::unique_ptr 与 new 的区别

c++ - 如何显示类中某些内容的枚举值?

c++ - CodeBlocks Qt HelloWorld.exe 已停止工作 (C++)