【问题标题】:How to display a TBitmap with alpha channel on TImage correctly?如何在 TImage 上正确显示带有 alpha 通道的 TBitmap?
【发布时间】:2013-07-10 23:24:54
【问题描述】:

我有一个 TBitmap,它包含带有 alpha 通道的半透明图像(在这个例子中,我从 TPngImage 得到它)。

var
  SourceBitmap: TBitmap;
  PngImage: TPngImage;
begin
  PngImage := TPngImage.Create();
  SourceBitmap := TBitmap.Create();
  try
    PngImage.LoadFromFile('ImgSmallTransparent.png');
    SourceBitmap.Assign(PngImage);
    SourceBitmap.SaveToFile('TestIn.bmp');
    imgSource.Picture.Assign(SourceBitmap);
  finally
    PngImage.Free();
    SourceBitmap.Free();
  end;

当我将此 TBitmap 保存到 TestIn.bmp 文件并使用任何图像查看器打开它时,我可以看到透明度。但是当我将它分配给 TImage 时,透明像素显示为黑色(TImage 有Transparent = True)。

如何在 TImage 上正确显示透明的 TBitmap?

【问题讨论】:

  • 请复制粘贴部分真实代码。
  • 如果所有的底层 wincontrols 都没有 Doublebuffered=true 并且图像未设置为透明,那么一切都按我的预期工作。

标签: delphi gdi timage tbitmap


【解决方案1】:

如果我对 imgSource 使用 Transparent=false,您显示的代码在我的系统上运行良好。
如果我从文件中加载位图,我可以重现黑色像素的行为。

不同的设置影响显示

procedure TForm3.SetAlphaFormatClick(Sender: TObject);
begin
  if SetAlphaFormat.Checked then
    ToggleImage.Picture.Bitmap.alphaformat := afDefined
  else
    ToggleImage.Picture.Bitmap.alphaformat := afIgnored;
end;

procedure TForm3.SetImageTransparentClick(Sender: TObject);
begin
  ToggleImage.Transparent := SetImageTransparent.Checked;
  Image1.Transparent := SetImageTransparent.Checked;
end;

procedure TForm3.LoadPngTransform2BitmapClick(Sender: TObject);
Const
  C_ThePNG = 'C:\temp\test1.png';
  C_TheBitMap = 'C:\temp\TestIn.bmp';
var
  SourceBitmap, TestBitmap: TBitmap;
  pngImage: TPngImage;
begin

  Image1.Transparent := SetImageTransparent.Checked;
  pngImage := TPngImage.Create;
  SourceBitmap := TBitmap.Create;
  TestBitmap := TBitmap.Create;
  try
    pngImage.LoadFromFile(C_ThePNG);
    SourceBitmap.Assign(pngImage);

    {v1 with this version without the marked* part, I get the behavoir you described
      SourceBitmap.SaveToFile(C_TheBitMap);
      TestBitmap.LoadFromFile(C_TheBitMap);
      TestBitmap.PixelFormat := pf32Bit;
      TestBitmap.HandleType := bmDIB;
      TestBitmap.alphaformat := afDefined;  //*
      Image1.Picture.Assign(TestBitmap);
    }
    //> v2
    SourceBitmap.SaveToFile(C_TheBitMap);
    SourceBitmap.PixelFormat := pf32Bit;
    SourceBitmap.HandleType :=  bmDIB;
    SourceBitmap.alphaformat := afDefined;
    Image1.Picture.Assign(SourceBitmap);
    //< v2
  finally
    pngImage.Free;
    SourceBitmap.Free;
    TestBitmap.Free;
  end;
end;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    • 2011-03-07
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2021-09-27
    • 2019-06-08
    相关资源
    最近更新 更多