简短回答:
在您的QImage
构造函数中使用Format_RGB32
而不是Format_Indexed8
。
详细回答:
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);
同时,您还可以手动为当前颜色表设置每个索引:
image->setColorCount(4);
image->setColor(0, qRgb(255, 0, 0));
image->setColor(1, qRgb(0, 0, 255));
image->setColor(2, qRgb(0, 0, 0));
image->setColor(3, qRgb(255, 255, 0));
image->fill(1);
如您所见,Format_Indexed8
像素值表示的不是 RGB 颜色,而是索引值(这些索引值再代表你在调色板中设置的颜色)。
Format_Mono
是另一种使用调色板的格式(请注意,该格式只允许两种颜色)。
附加答案:
其中一个颜色应为透明,另一个颜色可以是任意其他颜色(例如红色)。
如果我理解正确,以下代码将满足您的要求:
QImage *image = new QImage(256, 256, QImage::Format_Mono);
image->setColorCount(2);
image->setColor(0, qRgba(255, 0, 0, 255));
image->setColor(1, qRgba(0, 0, 0, 0));
for (short x = 0; x < 256; ++x) {
for (short y = 0; y < 256; ++y) {
if (y < 128) {
image->setPixel(x, y, 0);
}
else {
image->setPixel(x, y, 1);
}
}
}
QImage(400, 400, QImage::Format_ARGB32);
会怎样呢? - vahancho