37 Votes

Delphi: CanvasTextOut: Align Left, Right and Center

Tip by Delphian | Last update on 2023-01-31 | Created on 2013-02-13

CanvasTextOut is a Delphi function allowing us to draw a text on a bitmap. Unfortunately, this function does not support a native alignment of the text. So, in this tip, I want to show you a way, how to align the text left, right or centered using CanvasTextOut.

The trick with this: We determine the width of the text (variable textwidth) and we look up how much space is there for the text at all. Depending on the chosen alignment (in the examples given by the RadioButtons rb_alleft, rb_alright and rb_alcenter), we calculate the variable align, which we add to the margin when outputting.

Here is a full source code example:

procedure ...;
var
  lines: TStringList;
  i: integer;
  align, width, height, marginleft, marginright, margintop, 
  lineheight, position, textwidth: integer;
  bmp: TBitmap;
begin
  // lines that should be written
  lines:=TStringList.Create;
  lines.add('This is a text.');
  lines.add('This is another line.');

  // margins
  width       := 300;
  height      := 300;
  marginleft  := 10;
  marginright := 10;
  margintop   := 30;
  lineheight  := 40;

  // create bitmap
  bmp:=TBitmap.Create;
  bmp.Width  := width;
  bmp.height := height;

  // write text
  for i := 0 to length(lines) - 1 do
  begin
    // Ausrichtung
    textwidth:=CanvasTextWidth(bmp.Canvas, lines[i]);
    if rb_alleft.checked then
      align:=0;
    if rb_alright.checked then
      align:=width-marginleft-marginright-textwidth;
    if rb_alcenter.checked then
      align:=round((width-marginleft-marginright-textwidth)/2);

    // write lines
    position:=margintop+(i*lineheight);
    CanvasTextOut(bmp.Canvas, marginleft+align, position, lines[i]);
  end;

  // do something with the created bitmap
  Image1.Picture.Bitmap:=bmp;

  // free
  lines.Free;
  bmp.Free;
end;

First, we add some lines to a StringList. These lines should be outputted later. After that, we specify all margins and the size of the bitmap (you can change these values as you want). After we have created the bitmap, we go through the lines and we are determining the width of each lines. Next, we specify the align value for each line and we are writing each line onto the bitmap.

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.