Tinting a QPixmap using QPainter (CompositionMode_Overlay)
I'm having some issues tinting a QPixmap.
My code is:
image.load(imagePath); // load the image QPainter *paint = new QPainter(&image); paint->setCompositionMode(QPainter::CompositionMode_Overlay); // I want the box to blend into the image QRectF rectangle(0.0, 0.0, 45, 45); // the rectangle color.setAlpha(brightness); // I am setting the alpha so that the colour is actually visible paint->fillRect(rectangle, color); // this is the issue - it changes the alpha on the image, I want the alpha 255 pixels to be coloured in, not alpha 0. delete paint; color = colors; brightness = brightnessSlider; return image;
The problem is that the source image has a transparent background (alpha 0), and my sprite, has pixels which are opaque (alpha 255). However, the overlay mode ignores this, and decides to tint all of my source image.
The mode 'CompositionMode_Atop' sort of works, however it does not have the same desired effect as the Overlay mode.
Ideally, I would like the result to have a transparent background, and also to be tinted using the Overlay mode.
Maybe you have tried it, but i wonder if you could use the
with painter setClipRegion
so you only affect the area you want.
You can do this in two steps:
QPainter p; QImage img(imagePath); QImage mask(img); p.begin(&mask); p.setCompositionMode(QPainter::CompositionMode_SourceIn); p.fillRect(rect, color); p.end(); p.begin(&img); p.setCompositionMode(QPainter::CompositionMode_Overlay); p.drawImage(0, 0, mask); p.end(); return img;
Btw. Don't create painters on the heap. Dynamic allocation is slower than stack values. It also requires lifetime management (delete) which makes your code unnecessary complex.