问题描述
我有一个TBitmap,其中包含带有alpha通道的半透明图像(在本示例中,我是从TPngImage获得的)。
I have a TBitmap which contains semi-transparent image with alpha channel (in this example I got it from 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
)。
When I save this TBitmap to a TestIn.bmp
file and open it with any image viewer, I can see the transparency. But when I assign it to TImage, transparent pixels appear as black (TImage has Transparent = True
).
如何在TImage上正确显示具有透明性的TBitmap?
How to display TBitmap with transparency correctly on TImage?
推荐答案
如果我对imgSource使用Transparent = false,则显示的代码在我的系统上可以正常工作
如果从文件中加载位图,则可以用黑色像素重现行为。
Your shown code works fine on my system if I use Transparent=false for imgSource.
I can reproduce the behavoiur with the black pixels if I load the bitmap from a file.
不同的设置会影响显示的
Different setting influence the displaying
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;
这篇关于如何在TImage上正确显示带有Alpha通道的TBitmap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!