Adrian Maire
Adrian Maire

Reputation: 14845

How to apply alpha channel on drawPixmap with SourceOver

I am trying to understand the different composition modes of QPainter, but the alpha channel still obscure for me.

Lets see the following example:

QPainter painter(this);
painter.setCompositionMode(QPainter::CompositioMode_SourceOver);
painter.drawPixmap(rect(), QPixmap(":/Background_1.png"));
painter.setCompositionMode(QPainter::CompositioMode_SourceAtop);
painter.drawPixmap(rect(), QPixmap(":/Background_2.png"));

The first image is drawn correctly with alpha channel. The second image should only cover those part that are not transparent in the first image, but it actually cover 100%.

Lets see the second example:

QPainter painter(this);
painter.setCompositionMode(QPainter::CompositioMode_Source); //Changed here
painter.drawPixmap(rect(), QPixmap(":/Background_1.png"));
painter.setCompositionMode(QPainter::CompositioMode_SourceAtop);
painter.drawPixmap(rect(), QPixmap(":/Background_2.png"));

In this case, the first image apply without alpha channel, but the second image is applied correctly (only on covering non-transparent regions of the image_1).

My question is:

How to apply the first image with SourceOver capabilities, and then the second image with SourceAtop (with destination alpha of the first image)?

First and second example

Upvotes: 2

Views: 2639

Answers (1)

svlasov
svlasov

Reputation: 10455

You need to compose on separate buffers.

QPainter painter;

QImage image(size(), QImage::Format_ARGB32);
image.fill(0);

painter.begin(&image);
painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
painter.drawPixmap(rect(), QPixmap("Background_1.png"));
painter.setCompositionMode(QPainter::CompositionMode_SourceAtop);
painter.drawPixmap(rect(), QPixmap("Background_2.png"));
painter.end();

painter.begin(this);
painter.drawPixmap(rect(), QPixmap("clouds-05.jpg"));
painter.drawImage(rect(), image);
painter.end();

enter image description here enter image description here enter image description here

Upvotes: 4

Related Questions