Thursday, February 25, 2010

Draw Rotated Text

Current version of Lazarus provides the ability to draws text in an arbitrary rotation angle. Although is needed just to set the TFont.Orientation property to configure the feature, the position of the draw text will change according to the angle. So, to make things easier, i wrote a routine that draws a rotated text centered in a given Rect.

If someone needs something similar:


type
TRotateType = (rtNone, rtCounterClockWise, rtClockWise, rtFlip);

procedure DrawRotateText(Canvas: TCanvas; const R: TRect;
const Text: String; RotateType: TRotateType);
var
TextExtent: TSize;
SavedOrientation: Integer;
begin
SavedOrientation := Canvas.Font.Orientation;
TextExtent := Canvas.TextExtent(Text);
case RotateType of
rtNone:
begin
Canvas.Font.Orientation := 0;
Canvas.TextOut((R.Right - R.Left - TextExtent.cx) div 2,
(R.Bottom - R.Left - TextExtent.cy) div 2, Text);
end;
rtCounterClockWise:
begin
Canvas.Font.Orientation := 900;
Canvas.TextOut((R.Right - R.Left - TextExtent.cy) div 2,
(R.Bottom - R.Left + TextExtent.cx) div 2, Text);
end;
rtFlip:
begin
Canvas.Font.Orientation := 1800;
Canvas.TextOut((R.Right - R.Left + TextExtent.cx) div 2,
(R.Bottom - R.Left + TextExtent.cy) div 2, Text);
end;
rtClockWise:
begin
Canvas.Font.Orientation := -900;
Canvas.TextOut((R.Right - R.Left + TextExtent.cy) div 2,
(R.Bottom - R.Left - TextExtent.cx) div 2, Text);
end;
end;
Canvas.Font.Orientation := SavedOrientation;
end;

8 comments:

Silvio Clécio • Blog said...

Ótima dica :)

Testei no Lazarus-0.9.28.2/FPC-2.2.4-3/Ubuntu-9.10 e funcionou primeira.

O blog esta show ;)

Luiz Américo said...

Valeu Silvio. Faltava testar no Linux. Você fez o serviço por mim...

rtfgvb754 said...
This comment has been removed by a blog administrator.
Fabio Luis Girardi said...

Show de bola! Era o que faltava para mim! Essa dica logo vai estar no meu projeto :D

luk2009 said...

TSize is now in the Types unit
in my lazarus 0.9.29.

Олег Забусов said...
This comment has been removed by the author.
Олег Забусов said...

hi luiz

good code but it works correctly only for r.left=r.top=0
all TexOut calls should look like

Canvas.TextOut(
R.Left + (R.Right - R.Left - TextExtent.cx) div 2,
R.Top + (R.Bottom - R.Top - TextExtent.cy) div 2,
Text);

regards!

Owen Mike said...

Great Post, I’ll be definitely coming back to your site. Keep the nice work up.

Affordable Logo Design