GDI+ DrawLine draws nothing

Viewed 191

Starting to use GDI+ in Delphi. Need to draw a couple smooth straight lines. For example trying to draw diagonal line on the form (from left top corner to right bottom) but nothing appear. What's wrong with that code (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, 0, 0, ClientWidth, ClientHeight);
    finally
      gpPen.Free;
    end;
  finally
    graphics.Free;
  end;
end;

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

end.

enter image description here

1 Answers

The problem is the colour.

This is a GDI+ colour, which is not the same thing as a TColor which is essentially a Win32 COLORREF.

You pass clBlue = $00FF0000 which now is (mis)interpreted as (alpha, red, green, blue) = ($00, $FF, $00, $00). Since the alpha value is 0, the line is fully transparent.

If you do

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

instead, you get full opacity. But you get red, not blue, since the TColor is $00BBGGRR instead of $00RRGGBB. So if you do

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

you get your desired blue colour.

Better perhaps is to use the MakeColor function:

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

Or ColorRefToARGB:

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