使用Delphi XE在运行时将png图像添加到图像列表

Sal*_*dor 10 delphi delphi-xe

我需要在运行时添加一个png图像到TImageList.我已经看过了它实现的功能,TCustomImageList但它们只允许添加

  • 位图,
  • 图标或
  • 来自其他图像列表的图像

例如:

function Add(Image, Mask: TBitmap): Integer;
function AddIcon(Image: TIcon): Integer;
function AddImage(Value: TCustomImageList; Index: Integer): Integer;
procedure AddImages(Value: TCustomImageList);
function AddMasked(Image: TBitmap; MaskColor: TColor): Integer;
Run Code Online (Sandbox Code Playgroud)

如何在不将此图像转换为BMP的情况下将PNG图像添加到ImageList组件?

IDE已经可以在设计时将PNG添加到ImageList:

在此输入图像描述

现在我们需要在运行时完成它.

小智 20

Delphi XE具有处理png图像和带alpha通道的32位位图的所有支持.以下是如何将png添加到ImageList:

var pngbmp: TPngImage;
    bmp: TBitmap;
    ImageList: TImageList;
begin
  ImageList:=TImageList.Create(Self);
  ImageList.Masked:=false;
  ImageList.ColorDepth:=cd32bit;
  pngbmp:=TPNGImage.Create;
  pngbmp.LoadFromFile('test.png');
  bmp:=TBitmap.Create;
  pngbmp.AssignTo(bmp);
  // ====================================================
  // Important or else it gets alpha blended into the list! After Assign
  // AlphaFormat is afDefined which is OK if you want to draw 32 bit bmp
  // with alpha blending on a canvas but not OK if you put it into
  // ImageList -- it will be way too dark!
  // ====================================================
  bmp.AlphaFormat:=afIgnored;
  ImageList_Add(ImageList.Handle, bmp.Handle, 0);
Run Code Online (Sandbox Code Playgroud)

你必须包括

ImgList,PngImage

如果您现在尝试:

  Pngbmp.Draw(Bmp1.Canvas,Rect);
and
  ImageList.Draw(Bmp1.Canvas,0,0,0,true);
Run Code Online (Sandbox Code Playgroud)

你会看到图像是一样的.实际上,由于alpha混合过程中的舍入误差,有几个\ pm 1 rgb差异,但你无法用肉眼看到它们.忽略设置bmp.AlphaFormat:= afIgnored; 会导致第二张图像更暗!

最好的祝福,

亚历克斯

  • 将 CommCtrl 置于 uses 子句以使 ImageList_Add() 可用。 (2认同)

Uwe*_*abe 4

根据 MSDN,图像列表只能包含位图和图标。要将 png 图像添加到图像列表,您必须首先将其转换为图标。可以在PngComponents包中找到执行此操作的代码。如果您的图像列表中只有 PNG 图像,为了简单起见,您可以使用该包附带的 TPngImageList。