Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to assign the Canvas's font to change font size in Delphi 2009?

I've got an subclass of TPanel which I love so very very much and much to my chagrin, the font never seems to take when doing this:

font.size := AFontsize;
font.style := AFontStyle;
font.color := AFontColor;

but it does change when I do this:

Canvas.Font.Assign(Font);

I didn't have to do that in Delphi 7, but I seem to have to do it in 2009. What's the deal?

like image 742
Peter Turner Avatar asked Oct 14 '11 19:10

Peter Turner


1 Answers

If you paint text in the panel using its canvas, you must set the canvas font.

Some components and/or some Delphi versions can, either intentionally or as a side effect of a prior painting task, set Canvas.Font, but you shouldn't rely on it.

So it's recommended to do Canvas.Font := Font; prior to begin painting text.

The same applies to Canvas.Brush and Canvas.Pen.

type
  TMyPanel = class(TCustomPanel)
  protected
    procedure Paint; override;
  end;

procedure TMyPanel.Paint;
var
  r: TRect;
begin
  r := ClientRect;

  Canvas.Brush.Color := Color;
  Canvas.FillRect(r); // fill the background

  Canvas.Font := Font;
  DrawText(Canvas.Handle, 'Sample Text', -1, r, DT_SINGLELINE or DT_CENTER or DT_VCENTER or DT_EXPANDTABS or DT_NOPREFIX);
end;
like image 67
JRL Avatar answered Nov 08 '22 22:11

JRL