Michael Hutter
Michael Hutter

Reputation: 1532

Assign a picture to a TImage and define the background color of transparent pixels

Problem: I have a TImage on a Delphi VCL form and want to assign a TGraphic.
The picture has transparent pixels.
When displaying the picture inside the TImage I want to display all transparent pixels in the color clBlue. Unfortunately TImage does not have a property for a background color.

What I have already tried:

Fill the TImage with blue and afterwards to assign the picture:

MyImage.Canvas.Brush.Style := bsSolid;
MyImage.Canvas.Brush.Color := clBlue;
MyImage.Canvas.FillRect(Rect(0, 0, MyImage.Width, MyImage.Height));
MyImage.Picture.Assign(MyGraphic);

Set the TransparentColor of the bitmap:

MyImage.Picture.Bitmap.TransparentColor := clBlue;
MyImage.Picture.Assign(MyGraphic);

Nothing worked :-(

Upvotes: 1

Views: 731

Answers (2)

Michael Hutter
Michael Hutter

Reputation: 1532

procedure DrawPictureWithBackgroundColor(Image: TImage; Graphic: TGraphic; BackgroundColor: TColor);
begin
  Image.Canvas.Brush.Style := bsSolid;
  Image.Canvas.Brush.Color := BackgroundColor;
  Image.Canvas.FillRect(Rect(0, 0, Image.Width, Image.Height));
  Image.Canvas.StretchDraw(Rect(0, 0, Image.Width, Image.Height), Graphic);
end;

Usage:

DrawPictureWithBackgroundColor(MyImage, MyGraphic, clBlue);

MyGraphic contains the picture data itself.
MyImage is the control/container which makes the picture visible on the form.

Upvotes: 2

Remy Lebeau
Remy Lebeau

Reputation: 595981

Create a new TBitmap of the desired size, and fill it completely with a solid clBlue color.

Then, draw the source image transparently onto this TBitmap, so that the blue color shows through the transparent areas.

Then, assign this TBitmap to the TImage.


Alternatively, place the TImage onto a TPanel, set the panel's color to clBlue, and then assign the transparent image as-is to the TImage.


Alternatively, use a TPaintBox instead of a TImage. In the TPaintBox.OnPaint event, draw a clBlue background onto the TPaintBox.Canvas, then draw the source image transparently onto the Canvas.

Upvotes: 4

Related Questions