2

I need to draw text in the center of a box. The text must be drawn horizontally aligned with one char on each line.

I have attached an example with the string, "class".

enter image description here

I can draw the single char but I hope there is a faster way to do it.

Argalatyr
  • 4,639
  • 3
  • 36
  • 62
Martin
  • 1,065
  • 1
  • 17
  • 36
  • @LURD I don't need change the text angle... – Martin Mar 02 '14 at 14:05
  • use `Canvas.TextHeight()` to determine char height, make a counter `for i=1 to length(text)` and `Canvas.TextOut(50, i*(textheight+2), text[i])`. Something like that maybe? – rsrx Mar 02 '14 at 14:16

1 Answers1

7
procedure DrawVert(Canvas: TCanvas; Box: TRect; const Text: string);
var
  i: Integer;
  s: string;
  R: TRect;
begin
  s := '';
  for i := 1 to Length(Text) do
    s := s + Text[i] + ' ';
  R := Rect(0, 0, 1, 0);
  Canvas.TextRect(R, s, [tfCalcRect, tfNoClip, tfWordBreak]);
  Box.Left := Box.Left + (Box.Right - Box.Left - R.Right) div 2;
  Box.Top := Box.Top + (Box.Bottom - Box.Top - R.Bottom) div 2;
  Box.Right := Box.Left + R.Right;
  Box.Bottom := Box.Top + R.Bottom;
  Canvas.TextRect(Box, s, [tfWordBreak]);
end;

For testing, let PaintBox1 is the box we're painting on

procedure TForm1.Button1Click(Sender: TObject);
begin
  DrawVert(PaintBox1.Canvas, PaintBox1.Canvas.ClipRect, 'CLASS TEST');
end;
Sertac Akyuz
  • 54,131
  • 4
  • 102
  • 169
  • You should probably set s := '' at the start of the function otherwise you may end up with unpredictable results. – norgepaul Mar 02 '14 at 17:44
  • @norgepaul Well, this is a local and so it will be implicitly initialised to nil, but I would always refer to see this initialised explicitly. – David Heffernan Mar 02 '14 at 17:45
  • @norge - See answers to http://stackoverflow.com/questions/861045/which-variables-are-initialized-when-in-delphi . But ok, I don't see any reason to cause confusion, incorporated your suggestion... – Sertac Akyuz Mar 02 '14 at 17:53