QImage::fill(Qt::red) 总是黑色?

hon*_*a10 4 c++ user-interface qt colors qimage

我想弄清楚 QImage 是如何工作的。首先,我只想创建一个 400x400 像素的 QImage 并尝试将其填充为红色。那么 QImage 已填充但黑色...我也想创建一个单色 QImage。一种颜色应该是透明的,另一种颜色应该是其他颜色(例如:红色)。我怎样才能做到这一点?我用 setcolor 尝试过,但这似乎不起作用......

scene = new QGraphicsScene(this);
ui.graphicsView->setScene(scene);
QImage *image = new QImage(400, 400, QImage::Format_Indexed8); //QImage::Format_Mono);
image->fill(Qt::red);
//image->setColor(1, Qt::transparent);
//image->setColor(0, Qt::red);
scene->addPixmap(QPixmap::fromImage(*image));
Run Code Online (Sandbox Code Playgroud)

kef*_*500 6

简短回答:

在构造函数中使用Format_RGB32而不是。Format_Indexed8QImage

详细解答:

Format_Indexed8使用手动定义的颜色表,其中每个索引代表一种颜色。您必须为您的图像创建自己的颜色表:

QVector<QRgb> color_table;
for (int i = 0; i < 256; ++i) {
    color_table.push_back(qRgb(i, i, i)); // Fill the color table with B&W shades
}
image->setColorTable(color_table);
Run Code Online (Sandbox Code Playgroud)

您还可以手动设置当前颜色表的每个索引:

image->setColorCount(4); // How many colors will be used for this image
image->setColor(0, qRgb(255, 0, 0));   // Set index #0 to red
image->setColor(1, qRgb(0, 0, 255));   // Set index #1 to blue
image->setColor(2, qRgb(0, 0, 0));     // Set index #2 to black
image->setColor(3, qRgb(255, 255, 0)); // Set index #3 to yellow
image->fill(1); // Fill the image with color at index #1 (blue)
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,Format_Indexed8像素值代表的不是RGB 颜色,而是索引值(索引值又代表您在颜色表中设置的颜色)。

Format_Mono是另一种也使用颜色表的格式(请注意,其中只允许两种颜色)。

补充答案:

一种颜色应该是透明的,另一种颜色应该是其他颜色(例如:红色)。

如果我正确理解你的意思,这段代码将执行你想要的操作:

// Create a 256x256 bicolor image which will use the indexed color table:

QImage *image = new QImage(256, 256, QImage::Format_Mono);

// Manually set our colors for the color table:

image->setColorCount(2);
image->setColor(0, qRgba(255, 0, 0, 255)); // Index #0 = Red
image->setColor(1, qRgba(0, 0, 0, 0));     // Index #1 = Transparent

// Testing - Fill the image with pixels:

for (short x = 0; x < 256; ++x) {
    for (short y = 0; y < 256; ++y) {
        if (y < 128) {
            // Fill the part of the image with red color (#0)
            image->setPixel(x, y, 0);
        }
        else {
            // Fill the part of the image with transparent color (#1)
            image->setPixel(x, y, 1);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)