GDI+ DrawLine 什么也不画

问题描述

开始在 Delphi 中使用 GDI+。需要画几条平滑的直线。例如,试图在表单上绘制对角线(从左上角到右下角),但什么也没出现。该代码有什么问题(Delphi XE3、Windows 10 x64)?

unit Unit2;

interface

uses
  Winapi.Windows,Winapi.Messages,System.SysUtils,System.Variants,System.Classes,Vcl.Graphics,Vcl.Controls,Vcl.Forms,Vcl.Dialogs,Winapi.GDIPAPI,Winapi.GDIPOBJ;

type
  TForm2 = class(TForm)
    procedure FormPaint(Sender: TObject);
    procedure FormResize(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

procedure TForm2.FormPaint(Sender: TObject);
var
  graphics: TGPGraphics;
  gpPen: TGPPen;
begin
  graphics := TGPGraphics.Create(Self.Canvas.Handle);
  try
    graphics.SetSmoothingMode(SmoothingModeAntiAlias8x8);
    gpPen := TGPPen.Create(clBlue,3);
    try
      graphics.DrawLine(gpPen,ClientWidth,ClientHeight);
    finally
      gpPen.Free;
    end;
  finally
    graphics.Free;
  end;
end;

procedure TForm2.FormResize(Sender: TObject);
begin
  Repaint;
end;

end.

enter image description here

解决方法

问题在于颜色。

这是一个 GDI+ colour,它与本质上是 Win32 TColorCOLORREF 不同。

您通过了 clBlue = $00FF0000,现在(错误)解释为 (alpha,red,green,blue) = ($00,$FF,$00,$00)。由于 alpha 值为 0,因此线条完全透明。

如果你这样做

gpPen := TGPPen.Create(clBlue or $FF000000,3);

相反,您将获得完全不透明度。但是你得到的是红色而不是蓝色,因为 TColor$00BBGGRR 而不是 $00RRGGBB。所以如果你这样做

gpPen := TGPPen.Create($FF0000FF,3);

你得到你想要的蓝色。

也许最好使用 MakeColor 函数:

gpPen := TGPPen.Create(MakeColor(0,$FF),3)

ColorRefToARGB

gpPen := TGPPen.Create(ColorRefToARGB(clBlue),3)