Mirror

How to create transparent bitmaps (Views: 712)


Problem/Question/Abstract:

What I'd like to see is an image component which can be positioned over other windows/ images and use their respective canvases to fill-in its transparent color. My question is, does this component use as its background the bitmap of the window(s)/ device context(s) which it covers?

Answer:

Here's an excerpt of code that draws a transparent bitmap. I still use a mask, but the program does it for me. And, yes it is easy to draw over other graphic controls, all you need to do is to grab the form's canvas before drawing.


{ ... }
if (FTmpComp.Transparent) and (FTmpComp.CellMask.Width = 0) then
  {need to draw w/out cellmask}
try
  {Setup temp bitmaps}
  TmpBitmap := TBitmap.Create;
  TmpBitmap.Height := FTmpComp.Height;
  TmpBitmap.Width := FTmpComp.Width;
  MskBitmap := TBitmap.Create;
  MskBitmap.Height := FTmpComp.Height;
  MskBitmap.Width := FTmpComp.Width;
  MskBitmap.Monochrome := True;
  ImgBitmap := TBitmap.Create;
  ImgBitmap.Height := FTmpComp.Height;
  ImgBitmap.Width := FTmpComp.Width;
  {Create Mask}
  MskBitmap.Canvas.Brush.Color := clWhite;
  MskBitmap.Canvas.BrushCopy(DRect, FTmpComp.CellPicture, SRect,
    FTmpComp.CellPicture.Canvas.Pixels[0, 0]);
  MskBitmap.Canvas.CopyMode := cmSrcInvert;
  MskBitmap.Canvas.CopyRect(DRect, FTmpComp.CellPicture.Canvas, SRect);
  {Create 'blacked out' image}
  ImgBitmap.Canvas.CopyMode := cmNotSrcCopy;
  ImgBitmap.Canvas.CopyRect(Drect, MskBitmap.Canvas, DRect);
  ImgBitmap.Canvas.CopyMode := cmSrcAnd;
  ImgBitmap.Canvas.CopyRect(DRect, FTmpComp.CellPicture.Canvas, SRect);
  {Copy background from FPicture into the temp bitmap}
  TmpBitmap.Canvas.CopyMode := cmSrcCopy;
  TmpBitmap.Canvas.CopyRect(DRect, FPicture.Canvas, FRect);
  {AND the mask into the background to provide 'cut-out'}
  TmpBitmap.Canvas.CopyMode := cmSrcAnd;
  TmpBitmap.Canvas.CopyRect(DRect, MskBitmap.Canvas, DRect);
  {PAINT the CellPicture into the hole}
  TmpBitmap.Canvas.CopyMode := cmSrcPaint;
  TmpBitmap.Canvas.CopyRect(DRect, ImgBitmap.Canvas, DRect);
  {finally copy the temp bitmap onto the main canvas}
  Canvas.CopyMode := cmSrcCopy;
  Canvas.CopyRect(FRect, TmpBitmap.Canvas, DRect);
  {mark the Cell as having been updated}
  FTmpComp.IsDirty := False;
finally
  {free the bitmaps}
  TmpBitmap.Free;
  MskBitmap.Free;
  ImgBitmap.Free;
end;

<< Back to main page