C++Builder Logo
How to draw a transparent bitmap Comment afficher un bitmap transparent

Drawing a transparent bitmap on a canvas is not trivial. It makes an intensive use of windows API functions.
You have to choose a background color that will not be used in the foreground. The background color will be the transparent color.
Then you have to create a mask containing only monochrome colors. The mask allows you to get the foreground pixels only. Then you have to combine the source bitmap and the mask to get the transparent bitmap.
Afficher un bitmap de façon transparent n'est pas une chose facile. Vous devez d'abord créer le bitmap en choisissant une couleur de fond qui ne sera pas utilisée dans l'image. Ensuite, il vous faudra créer un masque monochrome qui vous permettra de ne récupérer que les points de couleurs du bitmap qui doivent être affichés.
Et finalement, combiner le masque et le bitmap d'origine pour rendre le bitmap transparent.
Fortunately, thanks to the VCL, there is an easy way to do that. Simply, use a TImageList to draw the bitmap. TImageList has a method to add an image with its transparent color. Heureusement, grâce à la VCL, nous avons une méthode simple pour faire cela. Il suffit d'utiliser un TImageList.
TImageList gère les masques et génère un bitmap transparent. 

In the .h file : 

private : 
  void __fastcall TForm1::DrawTransparentBitmap(TCanvas *Canvas, 
               Graphics::TBitmap *Bitmap,TColor TransparentColor, 
                       int X,int Y); 

//Canvas is the canvas where to draw the bitmap 
//TransparentColor is the color of the background 
// X and Y are the X and Y coordinates of the canvas 

In the .cpp file : 

//--------------------------------------------------------------------------- 
void __fastcall TForm1::DrawTransparentBitmap(TCanvas *Canvas, 
         Graphics::TBitmap *Bitmap,TColor TransparentColor, 
                     int X,int Y) 

  TImageList *ImageList=new TImageList(this); 
  ImageList->Width=Bitmap->Width; 
  ImageList->Height=Bitmap->Height; 
  ImageList->AddMasked(Bitmap,TransparentColor); 
  ImageList->Draw(Canvas,X,Y,0); 
  delete ImageList; 
}


If the transparent color is the color of the bottom left pixel, TransparentColor could be defined as follows : Si la couleur de transparence est celle qui se trouve dans le pixel en bas à gauche, TransparentColor peut être défini comme suit :

TransparentColor=Bitmap->Canvas->Pixels[0][Bitmap->Height-1];