如何在Delphi中制作alpha透明TImage?

时间:2013-12-05 21:38:55

标签: image delphi transparency alpha-transparency

在表格上我有两个TImages。位于顶部的TImage应该是透明的,因此我们可以看到底层的内容。如何更改TImage透明度的级别?

实施例: enter image description here

2 个答案:

答案 0 :(得分:9)

通常的方法是将所有图形绘制到一个目标画布(可能是TImage的位图),但即使有很多重叠的TImages,也可以这样做。请注意,您不能重叠TWinControls 由于32位位图支持透明度,因此可以通过将包含的图形转换为位图(如果需要)来实现 通过设置Alphaformat:= afDefined,将使用来自alphachannel的透明度信息绘制位图 我们需要一个位图的副本,因为设置AlphaFormat会让我们放松像素信息 使用扫描线可以将副本中的像素信息传输到目标,将Alpha通道设置为所需的值。

“一劳永逸”的实施可能如下所示:

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;

enter image description here

答案 1 :(得分:0)

TImage本身(以及任何其他UI控件)不能在其他控件之上进行alpha混合。但是,您可以使用TImage类在TGIFImage内显示Alpha混合GIF图像。

相关问题