Re: Length of Delphi string in pixels

Posted by webmaster Guido on August 30, 2005

In Reply to: Length of a Delphi string in pixels posted by Johan P14205 on August 29, 2005

: How can I calculate the length of a string in pixels, not in characters?

In Delphi, the "length" of a text in pixels is called "width".

For a TLabel, it's easy: when its property AutoSize is True (the default), then Label.Width is equal to the width of the text that is shown, its "Caption".

But that's not the case for other components. Their WIDTH property does not size itself automatically to the string that you set into the component, such as: TEdit, TButton, and so on...

Solution 1: if the Delphi component has a "Canvas" property, then use TheComponent.Canvas.TextWidth. For example:

procedure TForm1.Measure1;
var
  W: integer;
begin
  // Width of the first item of a ListBox
  W := ListBox1.Canvas.TextWidth(ListBox1.Items[0]);
  ListBox1.Width := W + 30; 

Solution 2: if the component does NOT have a "Canvas" property, but another Canvas exists that uses the same FONT, then use the TextWidth of that Canvas. In most cases, you can use the Canvas of the Form, assuming that Form and component use the same Font.

procedure TForm1.Measure2;
var 
  W: integer;
begin
  // Width of Caption of a Button
  W := Canvas.TextWidth(Button1.Caption); // Form1.Canvas !
  Button1.Width := W + 8;
  
Solution 3: if the component does NOT have a "Canvas" property, create a temporary Bitmap object and use its Canvas.TextWidth. Don't forget to destroy the Bitmap when it's not needed anymore.
procedure TForm1.Measure3;
var 
  W: integer;
  BM: TBitmap; 
begin
  BM := TBitmap.Create;
  BM.Canvas.Font := Button1.Font;
  W := BM.Canvas.TextWidth(Button1.Caption); 
  BM.Free;
  Button1.Width := W + 8;