tags:

views:

694

answers:

1

Hi,

Problem in drawing a semi transparent PNG image on TBitmap object.

If the TBitmap's ,HandleType is set to bmDDB, then the canvas is drawn transparent. But the problem is it doesn't work on all kinds of machines (for ex: Windows on apple computers).

When a TBitmap's HandleType property is set to bmDIB, canvas background is drawn white.

bmp.HandleType := bmDIB;

I tried setting Brush style to bsClear. But it draws the transparent pixels in black color.

How can I draw an image preserving its transparency and smooth curved edges.

Thanks Pavan.

+2  A: 

It is certainly possible to paint a bmDIB bitmap with transparent background to a canvas:

procedure TForm1.FormPaint(Sender: TObject);
var
  Bmp: TBitmap;
begin
  Bmp := TBitmap.Create;
  try
    Bmp.PixelFormat := pf32bit;
    Bmp.HandleType := bmDIB;
    Bmp.Width := 700;
    Bmp.Height := 400;
    Bmp.Transparent := TRUE;
    Bmp.TransparentColor := clMaroon;

    with Bmp.Canvas do begin
      Brush.Color := clMaroon;
      FillRect(Rect(0, 0, Bmp.Width, Bmp.Height));

      Brush.Color := clBlue;
      FillRect(Rect(42, 42, 200, 300));
    end;

    Canvas.Draw(12, 12, Bmp);
  finally
    Bmp.Free;
  end;
end;

Note that the whole bitmap is filled first with the colour set as TransparentColor.

But for more control and speed you should look into a solution that is not as dependent on the GDI (which involves graphics card and driver capabilities), something like Graphics32.

mghie
+ 1 for Graphics32
Runner
Trying to load a png image which has semi transparent pixels on the corner edges. Using the above procedure those semi transparent pixels are drawn in black color.
Pavan
@Pavan: Transparent <> semitransparent. If you need the per-pixel alpha value you should either stay with a graphic format that fully supports it, or look into Graphics32. Or into GDI+. AFAIK there is no guarantee that you can do what you want with GDI and be sure it works on *all* systems.
mghie