2
votes

I've seen many questions asking how to draw transparent images, but my case is quite the opposite. I have a TPicture where I load any file type, including PNG. I then read TPicture.Graphic and call Draw directly in a TBitmap's canvas. However, when the image is drawn, it carries over the transparency of the original PNG image.

The current code is very simple, just...

MyPicture.LoadFromFile(SomeFilename);
MyBitmap.Canvas.StretchDraw(SomeRect, MyPicture.Graphic);

Now the issue is that the canvas which I'm drawing to already has an image, and this PNG is being drawn over a portion of it. When the PNG has a transparent background, normally it appears white. However, since it's directly drawing a transparent graphic to the canvas, it keeps those areas transparent.

How can I draw a PNG Graphic directly to a canvas without its original transparency while using only the canvas drawing methods? I don't want to create too many graphic objects and draw too many times, hence the reason I only have 2 lines of code above. I'm hoping there's a way I can do something like BitBlt with some special mechanism for this purpose.

1
Your question is ill-formed. If you don't want transparency, you need to say what you want in its place. Transparency is an absence of colour. What do you want instead?David Heffernan
@David, I edited my question for that exact reason just as you put that comment. I added more info about why it needs to be transparent, and why I don't want to create too much code to do it.Jerry Dodge
Can't you fillrect that portion just before you draw?Sertac Akyuz
@SertacAkyuz I must slap myself in the face for not thinking of that. Simple. Adds only 1 line of code (other than preparing the brush/pen). I'd accept that as an answer.Jerry Dodge
@Jerry - I already commented and upvoted on the answer which I believe is correct. It only misses the implementation, no big deal.Sertac Akyuz

1 Answers

6
votes

The only method pre-built in Delphi XE2 has a defect and doesn't work properly. Instead, draw whitespace, or whatever background you desire, to a blank canvas. Then draw the transparent image on top.

In case you aren't drawing onto a blank canvas, you can call FillRect method of the bitmap canvas for the region you're planning to draw the png.