Delphi - Populate an imagelist with icons at runtime 'destroys' transparency

夙愿已清 提交于 2019-12-03 14:15:51

To support alpha transparency, you need to create the image list and populate it at runtime:

function AddIconFromResource(ImageList: TImageList; ResID: Integer): Integer;
var
  Icon: TIcon;
begin
  Icon := TIcon.Create;
  try
    Icon.LoadFromResourceID(HInstance, ResID);
    Result := ImageList.AddIcon(Icon);
  finally
    Icon.Free;
  end;
end;

function AddPngFromResource(ImageList: TImageList; ResID: Integer): Integer;
var
  Png: TPngGraphic;
  ResStream: TStream;
  Bitmap: TBitmap;
begin
  ResStream := nil;
  Png := nil;
  Bitmap := nil;
  try
    ResStream := TResourceStream.CreateFromID(HInstance, ResID, RT_RCDATA);
    Png := TPNGGraphic.Create;
    Png.LoadFromStream(ResStream);
    FreeAndNil(ResStream);
    Bitmap := TBitmap.Create;
    Bitmap.Assign(Png);
    FreeAndNil(Png);
    Result := ImageList.Add(Bitmap, nil);              
  finally
    Bitmap.Free;
    ResStream.Free;
    Png.Free;
  end;
end;

// this could be e.g. in the form's or datamodule's OnCreate event
begin
  // create the imagelist
  ImageList := TImageList.Create(Self);
  ImageList.Name := 'ImageList';
  ImageList.DrawingStyle := dsTransparent;
  ImageList.Handle := ImageList_Create(ImageList.Width, ImageList.Height, ILC_COLOR32 or ILC_MASK, 0, ImageList.AllocBy);
  // populate the imagelist with png images from resources
  AddPngFromResource(ImageList, ...);
  // or icons
  AddIconFromResource(ImageList, ...);

end;

I had the exact same problems a couple of years ago. It's a Delphi problem. I ended up putting the images in the list at design time, even though I really didn't want to. I also had to use a DevExpress image list to get the best results and to use 32 bit color images.

As Jeremy said this is indeed a Delphi limitation.

One work around I've used for images that I was putting onto buttons (PNGs with alpha transparency in my case) is to store the PNGs as resources, and at run time paint them onto a button sized bitmap filled with clBtnFace. The bitmap was then used as the control's glyph.

Delphi's built in support for icons with alpha masks is very limited, however there's an excellent icon library kicon which may help.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!