绘制透明缩放PNG

Draw Transparent Scaled PNG

我有一张大 (300x300px) PNG 图像,需要重新缩放。在另一个 SO question 中,我阅读了 StretchBltHALFTONE 以便更好地缩放。

我的问题是如何将 PNG 图像绘制为透明,或者至少将黑角涂成白色?

正如您在所附图片中看到的那样,我得到了黑角。

这是原始图像: 到目前为止,这是我尝试过的。

unit MainU;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls;

type
  TFormMain = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  FormMain: TFormMain;

implementation

{$R *.dfm}
uses
  Pngimage;

type
  TIRButton = class(TImage)
  protected
    procedure Paint; override;
  public
    constructor Create(AOwner: TComponent); override;
  end;

  TGraphicControlAcess = class(TGraphicControl);
  TGraphicAcess = class(TGraphic);

  THalfTonePngImage = class(TPngImage)
  protected
    procedure Draw(ACanvas: TCanvas; const Rect: TRect); override;
  end;

  { TIRButton }

constructor TIRButton.Create(AOwner: TComponent);
begin
  inherited;
  Center := True;
  Proportional := True;
end;

procedure TIRButton.Paint;
var
  ParentCanvas: TCanvas;
begin
  ParentCanvas := TGraphicControlAcess(Self).Canvas;
  TGraphicAcess(Picture.Graphic).Draw(ParentCanvas, DestRect);
end;

{ THalfTonePngImage }

procedure THalfTonePngImage.Draw(ACanvas: TCanvas; const Rect: TRect);
var
  p: TPoint;
  dc: HDC;
begin
  dc := ACanvas.Handle;
  GetBrushOrgEx(dc, p);
  SetStretchBltMode(dc, HALFTONE);
  SetBrushOrgEx(dc, p.X, p.Y, @p);

  ACanvas.Brush.Color := clWhite;
  ACanvas.FillRect(Classes.Rect(0, 0, Width, Height));

  StretchBlt(
    dc, 0, Rect.Top, Rect.Right - Rect.Left, Rect.Bottom - Rect.Top,
    Canvas.Handle, 0, 0, Width, Height, ACanvas.CopyMode
    );
end;

procedure TFormMain.FormCreate(Sender: TObject);
var
  Image: THalfTonePngImage;
begin
  Image := THalfTonePngImage.Create;
  Image.LoadFromFile('X200IR_11_EmgBrake.png');

  with TIRButton.Create(Self) do
  begin
    Width := 100;
    Height := 100;
    Picture.Assign(Image);
    Parent := Self;
    Anchors := [akLeft, akTop, akRight, akBottom];
  end;

  Image.Free;
end;

end.

源图像的角是透明的。由于白色背景,它在正确的图像中不可见。 StretchBlt 不支持透明度。因为它没有,所以透明像素与黑色无法区分。 (如果 ARGB 颜色是 FF 00 00 00 并且我们删除了 alpha 通道,我们剩下 00 00 00

您需要使用 TransparentBlt.

作为参考,这是放置在绿色背景上的图像。更容易看到透明度。