22 Votes

Delphi/Lazarus: Specify TextWidth and TextHeight without Canvas

Question by Guest | Last update on 2022-07-21 | Created on 2016-01-17

I would like to determine the width and height for a font respectively for a specific font size (TextWidth and TextHeight) without having a Canvas available.

For example, a Button (TButton) does not have a Canvas. So, how should I work with that? Does someone have a trick for that?

ReplyPositiveNegativeDateVotes
4Best Answer4 Votes

When I am faced with that issue, I am creating a bitmap within the function at which I can process my measurements. After processing, I can delete (free) this bitmap in case that I do not need it anymore.

Here is a function to get the width (TextWidth) of a font:

function GetTextWidth(AText: string): integer;
var
  bmp: TBitmap;
begin
  bmp := TBitmap.Create;
  try
    bmp.Canvas.Font.Assign(self.Font);
    result := bmp.Canvas.TextWidth(AText);
  finally
    bmp.Free;
  end;
end;

And here is a function to get the height (TextHeight):

function GetTextHeight(AText: string): integer;
var
  bmp: TBitmap;
begin
  bmp := TBitmap.Create;
  try
    bmp.Canvas.Font.Assign(self.Font);
    result := bmp.Canvas.TextHeight(AText);
  finally
    bmp.Free;
  end;
end;

In both functions, we are taking over the font from Form1, but of course, it is also possible to use and set any other font to bmp.Canvas.Font within the function. For example like that:

function GetTextWidth(AText, AFontName: string; 
  AFontSize: integer): integer;
var
  bmp: TBitmap;
begin
  bmp := TBitmap.Create;
  try
    bmp.Canvas.Font.Name := AFont;
    bmp.Canvas.Font.Size := AFontSize;
    result := bmp.Canvas.TextWidth(AText);
  finally
    bmp.Free;
  end;
end;

In this function, we can also pass the name of the font as well as the font size as parameter.

However, if you only want to set the size of a Button, you can also do that by setting the property AutoSize to TRUE. If this is the case, the button automatically adjusts to the containing text.
Last update on 2022-07-21 | Created on 2016-01-18

ReplyPositive Negative
00 Votes

What is c, and why are you freeing it instead of bmp?
2022-07-21 at 18:35

Positive Negative
00 Votes

Thank you very much for reporting that issue.

It must be bmp not c, I have corrected that error in the example code.
2022-07-21 at 22:50

Positive Negative
Reply
Reply

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.