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

12

我需要在运行时向TImageList中添加一个png图像。我查看了TCustomImageList实现的函数,但它们只允许添加:

  • 位图,
  • 图标或
  • 来自另一个图像列表的图像

E.g.:

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;

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

IDE已经可以在设计时向ImageList添加PNG图像:

enter image description here

现在我们需要在运行时执行它。
3个回答

23

Delphi XE支持处理带有alpha通道的png图像和32位位图。以下是将png添加到ImageList的方法:

uses CommCtrl;

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);

您必须包含

ImgList、PngImage

如果您现在尝试:

  Pngbmp.Draw(Bmp1.Canvas,Rect);
and
  ImageList.Draw(Bmp1.Canvas,0,0,0,true);

你会发现这些图像是一样的。 实际上,由于 alpha 混合过程中的四舍五入误差,会出现几个 \pm 1 的 RGB 差异,但肉眼无法察觉。如果忽略设置 bmp.AlphaFormat:=afIgnored;,第二张图片将会比较暗!

最好的祝福,

alex


2
将CommCtrl添加到uses子句中,以便使ImageList_Add()可用。 - denim

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

2
  • 创建一个TPngImage实例,命名为PngImage: PngImage
  • 将图像加载到此实例中,使用PngImage.LoadFromFile(..)
  • 创建一个TBitmap实例,命名为Bitmap: TBitmap
  • 将PNG分配给位图,使用Bitmap.Assign(PngImage)
  • 将位图添加到图像列表中
  • 完成!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接