在表单上,我有两个TImage。顶部的TImage应该是透明的,因此我们可以看到下面的内容。如何更改TImage透明度的级别?
例子:
最佳答案
通常的方法是将所有图形绘制到一个目标 Canvas (可以是TImage的位图)上,但是即使有许多重叠的TImage也可以做到这一点。请注意,您不能重叠TWinControls。
由于32位位图支持透明性,可以通过将包含的图形转换为位图(如果需要)来实现。
通过设置Alphaformat:= afDefined,将使用来自alpha channel 的透明度信息绘制位图。
我们需要位图的副本,因为设置AlphaFormat将使我们失去像素信息。
使用扫描线,可以将副本中的像素信息传输到目标位置,将Alpha channel 设置为所需的值。
一个“即发即弃”的实现可能看起来像这样:
type
pRGBQuadArray = ^TRGBQuadArray;
TRGBQuadArray = ARRAY [0 .. 0] OF TRGBQuad;
procedure SetImageAlpha(Image:TImage; Alpha: Byte);
var
pscanLine32,pscanLine32_src: pRGBQuadArray;
nScanLineCount, nPixelCount : Integer;
BMP1,BMP2:TBitMap;
WasBitMap:Boolean;
begin
if assigned(Image.Picture) then
begin
// check if another graphictype than an bitmap is assigned
// don't check Assigned(Image.Picture.Bitmap) which will return always true
// since a bitmap is created if needed and the graphic will be discared
WasBitMap := Not Assigned(Image.Picture.Graphic);
if not WasBitMap then
begin // let's create a new bitmap from the graphic
BMP1 := TBitMap.Create;
BMP1.Assign(Image.Picture.Graphic);
end
else BMP1 := Image.Picture.Bitmap; // take the bitmap
BMP1.PixelFormat := pf32Bit;
// we need a copy since setting Alphaformat:= afDefined will clear the Bitmap
BMP2 := TBitMap.Create;
BMP2.Assign(BMP1);
BMP1.Alphaformat := afDefined;
end;
for nScanLineCount := 0 to BMP1.Height - 1 do
begin
pscanLine32 := BMP1.Scanline[nScanLineCount];
pscanLine32_src := BMP2.ScanLine[nScanLineCount];
for nPixelCount := 0 to BMP1.Width - 1 do
begin
pscanLine32[nPixelCount].rgbReserved := Alpha;
pscanLine32[nPixelCount].rgbBlue := pscanLine32_src[nPixelCount].rgbBlue;
pscanLine32[nPixelCount].rgbRed := pscanLine32_src[nPixelCount].rgbRed;
pscanLine32[nPixelCount].rgbGreen:= pscanLine32_src[nPixelCount].rgbGreen;
end;
end;
If not WasBitMap then
begin // assign and free Bitmap if we had to create it
Image.Picture.Assign(BMP1);
BMP1.Free;
end;
BMP2.Free; // free the copy
end;
procedure TForm3.Button1Click(Sender: TObject);
begin // call for the example image
SetImageAlpha(Image1,200);
SetImageAlpha(Image2,128);
SetImageAlpha(Image3,80);
end;
关于image - 如何在Delphi中使Alpha透明TImage?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20411314/