[Lazarus] Converting Icon from Windows handle to TBitmap with transparency

cobines cobines at gmail.com
Fri Jul 15 00:10:01 CEST 2011


2011/6/8 cobines <cobines at gmail.com>:
> Hello everyone.
>
> I want to convert an icon retrieved by Windows API to a TBitmap saving
> transparency. As I understand transparency can be achieved by:
> - using an additional Mask bitmap
> - using 32bpp TBitmap with alpha channel
>
> Having the handle to an icon from WINAPI, I convert it to TBitmap the
> following way:
>
> function IconToBitmap(h: HICON): TBitmap;
> var
>  icon: TIcon;
> begin
>  icon := TIcon.Create;
>  icon.Handle := h;
>  Result := TBitmap.Create;
>  Result.Assign(icon);
>  icon.Free;
> end;
>
> But this does not preserve transparency. I have to add:
>
> Result.Mask(Result.TransparentColor);
>
> Is this the correct way?
>
> Why Icon does not automatically have a Mask? It does have
> TransparentMode and TransparentColor correctly assigned.
> TransparentColor is copied to TBitmap but the Mask is not copied or
> not automatically created.

I finally had time to do some digging.

Turns out Mask bitmap exists in both TIcon and TBitmap (mask image is
copied). Problem is Masked is False in TBitmap. This is because in

procedure TRasterImage.Assign(Source: TPersistent);

there is line

    FMasked := SrcImage.FMasked;

which is wrong. It should be :

    FMasked := SrcImage.Masked;

FMasked is never set to True for TCustomIcon. Instead Masked property
is overridden to always return True. Therefore after
TBitmap.Assign(TIcon) FMasked is False, while it should be True.

Also a question:
Why TIcon always has Masked=True?

Icons with alpha channel don't work properly with TIcon and they don't
use Mask. Is support for alpha channel icons simply not implemented?

--
cobines




More information about the Lazarus mailing list