【问题标题】:Add stretched image to ImageList in Delphi在 Delphi 中将拉伸图像添加到 ImageList
【发布时间】:2023-06-02 11:27:01
【问题描述】:

我有一个包含图片字段中的图片的表格,我将把它们放入一个 ImageList 中。 代码如下:

ImageList.Clear;
ItemsDts.First;
ImageBitmap:= TBitmap.Create;
try
  while not ItemsDts.Eof do
  begin
    if not ItemsDtsPicture.IsNull then
    begin
      ItemsDtsPicture.SaveToFile(TempFileBitmap);
      ImageBitmap.LoadFromFile(TempFileBitmap);
      ImageList.Add(ImageBitmap, nil);
    end;
    ItemsDts.Next;
  end;
finally
  ImageBitmap.Free;
end;

但是对于大小与 ImageList 大小不同的图像,我遇到了一些问题。

更新: 我的问题是,当添加大于 ImageList 大小(32 * 32)的图像时,例如 100 * 150 它在连接到 ImageList 的组件中(例如在 ListView 中)没有正确显示。 似乎新添加的图像没有被拉伸,而是被裁剪。我希望像在 ImageList 编辑器中一样拉伸新图像。

【问题讨论】:

  • 这还不是问题。 “对于与 ImageList 大小不同的图像,我遇到了一些问题。”请准确描述问题所在,并提出一个具体、直接的问题。
  • 你有什么问题?图片看起来如何,您希望它们看起来如何?
  • @David Heffernan 和@Cosmin Prund:对不起。问题已更新...

标签: delphi stretch imagelist


【解决方案1】:

不知道ImageList是否提供了自动拉伸图片的属性。除非有人找到一些内置的,否则您始终可以在将图像添加到 ImageList 之前自己拉伸图像。当您使用它时,请停止使用磁盘上的文件:改用TMemoryStream。像这样的:

var StretchedBMP: TBitmap;
    MS: TMemoryStream;

ImageList.Clear;
ItemsDts.First;
StretchedBMP := TBitmap.Create;
try

  // Prepare the stretched bmp's size
  StretchedBMP.Width := ImageList.Width;
  StretchedBMP.Height := ImageList.Height;

  // Prepare the memory stream
  MS := TMemoryStream.Create;
  try
    ImageBitmap:= TBitmap.Create;
    try
      while not ItemsDts.Eof do
      begin
        if not ItemsDtsPicture.IsNull then
        begin
          MS.Size := 0;
          ItemsDtsPicture.SaveToStream(MS);
          MS.Position := 0;
          ImageBitmap.LoadFromStream(MS);
          // Stretch the image
          StretchedBMP.Canvas.StretchDraw(Rect(0, 0, StretchedBmp.Width-1, StretchedBmp.Height-1), ImageBitmap);
          ImageList.Add(StretchedBmp, nil);
        end;
        ItemsDts.Next;
      end;
    finally MS.Free;
    end;
  finally StretchedBMP.Free;
  end;
finally
  ImageBitmap.Free;
end;

PS:我在浏览器窗口中编辑了您的代码。我不能保证它可以编译,但如果没有,它应该很容易修复。

【讨论】:

  • 非常感谢。有用。也感谢您使用 MemoryStream。我之前尝试过使用 TMemoryStream,但不能。因为我不知道需要将大小和位置设置为零。
  • 但唯一的问题是图像现在不透明。所以我问另一个问题:*.com/questions/6688356/…
  • 你是这样的冠军,已经实现了在浏览器窗口中编写这段代码的壮举!