如何使用纯GDI对画布区域进行颜色混合(通过指定的alpha值着色)?

TLa*_*ama 9 delphi optimization winapi gdi

我想使用纯颜色混合(通过指定的alpha值着色)画布区域Windows GDI(因此没有GDI +,DirectX或类似,没有OpenGL,没有汇编程序或第三方库).

我创建了以下函数,我想知道是否有更高效或更简单的方法来执行此操作:

procedure ColorBlend(const ACanvas: HDC; const ARect: TRect;
  const ABlendColor: TColor; const ABlendValue: Integer);
var
  DC: HDC;
  Brush: HBRUSH;
  Bitmap: HBITMAP;
  BlendFunction: TBlendFunction;
begin
  DC := CreateCompatibleDC(ACanvas);
  Bitmap := CreateCompatibleBitmap(ACanvas, ARect.Right - ARect.Left,
    ARect.Bottom - ARect.Top);
  Brush := CreateSolidBrush(ColorToRGB(ABlendColor));
  try
    SelectObject(DC, Bitmap);
    Windows.FillRect(DC, Rect(0, 0, ARect.Right - ARect.Left,
      ARect.Bottom - ARect.Top), Brush);
    BlendFunction.BlendOp := AC_SRC_OVER;
    BlendFunction.BlendFlags := 0;
    BlendFunction.AlphaFormat := 0;
    BlendFunction.SourceConstantAlpha := ABlendValue;
    Windows.AlphaBlend(ACanvas, ARect.Left, ARect.Top,
      ARect.Right - ARect.Left, ARect.Bottom - ARect.Top, DC, 0, 0,
      ARect.Right - ARect.Left, ARect.Bottom - ARect.Top, BlendFunction);
  finally
    DeleteObject(Brush);
    DeleteObject(Bitmap);
    DeleteDC(DC);
  end;
end;
Run Code Online (Sandbox Code Playgroud)

有关此功能应该做什么的概念,请参阅以下内容(区分:-)图像:

在此输入图像描述 在此输入图像描述

并且代码可以this image以上面显示的方式呈现到表单的左上方:

uses
  PNGImage;

procedure TForm1.Button1Click(Sender: TObject);
var
  Image: TPNGImage;
begin
  Image := TPNGImage.Create;
  try
    Image.LoadFromFile('d:\6G3Eg.png');
    ColorBlend(Image.Canvas.Handle, Image.Canvas.ClipRect, $0000FF80, 175);
    Canvas.Draw(0, 0, Image);
  finally
    Image.Free;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

使用纯GDI或Delphi VCL有更有效的方法吗?

Fra*_*ois 4

您尝试过使用 AlphaBlend 进行 Canvas 绘图吗?

就像是

Canvas.Draw(Arect.Left, ARect.Top, ABitmap, AAlphaBlendValue);
Run Code Online (Sandbox Code Playgroud)

与 FillRect 结合用于混合颜色

更新:这里有一些代码,尽可能接近您的界面,但纯 VCL。
可能没有那么高效,但更简单(并且有些便携)。
正如 Remy 所说,要以伪持久方式在 Form 上绘画,您必须使用 OnPaint...

procedure ColorBlend(const ACanvas: TCanvas; const ARect: TRect;
  const ABlendColor: TColor; const ABlendValue: Integer);
var
  bmp: TBitmap;
begin
  bmp := TBitmap.Create;
  try
    bmp.Canvas.Brush.Color := ABlendColor;
    bmp.Width := ARect.Right - ARect.Left;
    bmp.Height := ARect.Bottom - ARect.Top;
    bmp.Canvas.FillRect(Rect(0,0,bmp.Width, bmp.Height));
    ACanvas.Draw(ARect.Left, ARect.Top, bmp, ABlendValue);
  finally
    bmp.Free;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Image: TPNGImage;
begin
  Image := TPNGImage.Create;
  try
    Image.LoadFromFile('d:\6G3Eg.png');
    ColorBlend(Image.Canvas, Image.Canvas.ClipRect, $0000FF80, 175);
    Canvas.Draw(0, 0, Image);
    // then for fun do it to the Form itself
    ColorBlend(Canvas, ClientRect, clYellow, 15);
  finally
    Image.Free;
  end;
end;
Run Code Online (Sandbox Code Playgroud)