Search code examples
qtqpainter

how to tint/highlight qpixmap only the area that has non-zero alpha


I have a QPixmap that has some transparent area. What can I do to apply a highlight/tint to only area that has non-zero alpha?

This is what I have right now, which tints the whole image.

QPixmap highlighedPixmap = myPixmap;
QPainter pixmapPainter;
pixmapPainter.begin(&highlighedPixmap);
pixmapPainter.setCompositionMode(QPainter::CompositionMode_ColorDodge);
pixmapPainter.fillRect(highlighedPixmap.rect(), QColor(180, 180, 180, 100));
pixmapPainter.end();

input image:

enter image description here

expected result image:

enter image description here


Solution

  • The right option is CompositionMode_SourceAtop:

    QPixmap highlighedPixmap = myPixmap;
    QPainter pixmapPainter(&highlighedPixmap);
    pixmapPainter.setCompositionMode(QPainter::CompositionMode_SourceAtop);
    pixmapPainter.fillRect(highlighedPixmap.rect(), foregroundColor);
    pixmapPainter.end();
    

    Within Qt directory in ...\examples\widgets\painting\composition, there is a "Composition Modes" tool, which lets you experiment with all composition modes. I found it in Qt 5.2.1 but it should be there at least since Qt 4.8.