Question

I'd like to use Qt 5.2 to create images with alpha in them, but I'm finding that the color values are being quantized. Here's an example:

QColor testColor(248, 64, 16, 2);

QImage image(10, 10, QImage::Format_ARGB32);

QPainter painter(&image);
painter.setCompositionMode(QPainter::CompositionMode_Source);
painter.fillRect(0, 0, 5, 5, testColor);
painter.end();

qDebug("Test color was (%d, %d, %d, %d)",
       testColor.red(), testColor.green(), testColor.blue(), testColor.alpha());

QRgb value = image.pixel(1, 1);
qDebug("QPainter painted (%d, %d, %d, %d)",
       qRed(value), qGreen(value), qBlue(value), qAlpha(value));

This prints out:

Test color was (248, 64, 16, 2)
QPainter painted (255, 127, 0, 2)

In my application, preserving the original red, green, and blue values is important. Is there a Qt option that I've missed or is this just the expected behavior of the Qt 2D renderer?

Was it helpful?

Solution

QPainter uses the Raster backend by default. It seems that this backend internally operates with premultiplied RGBA data. This causes data loss in RGB channels for low alpha. It seems that there is no simple way to change this behavior. You may try to use OpenGL or OpenVG backends if possible. Backends are described in this section of the docs. Another option is to implement rendering on QImage manually. You also can try to render RGB and alpha channel on 2 different images and somehow join them after that. See also this question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top