Jan Doggen
Jan Doggen

Reputation: 9106

Why do TPanel.Canvas.Font properties (accessed with protected hack) differ from TPanel.Font properties?

I'm using the DrawTextRotatedB function from Josef Švejk's excellent answer to the question How to draw text in a canvas vertical + horizontal with Delphi 10.2 to draw text vertically on a TPanel.
That component does not have a public Canvas property, so I'm using the protected hack to access it:

type
   THackPanel = class(TPanel);

DrawTextRotated(THackPanel(PnlLeftLeft).Canvas,90, PnlLeftLeft.Width DIV 2, cVertDrawOffset, FLeftVertText)

with definition

procedure DrawTextRotated(ACanvas: TCanvas; Angle, X, Y: Integer; AText: String);

The procedure uses ACanvas.Font properties to draw text using ACanvas.TextOut.
I noticed that inside the procedure these properties were not what I had expected, e.g.

PnlLeftLeft.Font.Size = 20
PnlLeftLeft.Font.Ttyle = [fsBold]

THackPanel(PnlLeftLeft).Canvas.Font.Size = 10
THackPanel(PnlLeftLeft).Canvas.Font.Ttyle = []

It seems that I can easily 'fix' this doing THackPanel(PnlLeftLeft).Canvas.Font := PnlLeftLeft.Font; right before the procedure call, but I'm still left with the question:

Why don't TPanel.Canvas.Font properties the mirror the TPanel.Font properties?

Upvotes: 2

Views: 239

Answers (1)

Andreas Rejbrand
Andreas Rejbrand

Reputation: 109003

This is by design.

A complex control may write text with different fonts at different times and locations, and so Canvas.Font – which dictates the font of the next text-drawing operation – may vary even during the painting of a single "frame".

Self.Font, on the other hand, is the "primary font" of the control, which is often displayed in the Object Inspector (being a published property) and affected by the ParentFont property.

For example, a control's painting code might assign Self.Font to Canvas.Font at the beginning of each invocation and then possibly alter it slightly during painting (maybe to draw some parts in italics or boldface or some different colour).

Upvotes: 5

Related Questions