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

Time:01-05

Problem: I have a TImage on a Delphi VCL form and want to assign a picture from a TImageList.
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(MyImageList[1]);

Set the TransparentColor of the bitmap:

MyImage.Picture.Bitmap.TransparentColor := clBlue;
MyImage.Picture.Assign(MyImageList[1]);

Nothing worked :-(

CodePudding user response:

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, MyImageList[1], clBlue);

CodePudding user response:

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.

  • Related