13

Here is my problem, I want to know actual length of the text in pixels (note that various letters have different length in some fonts). I am going to use this for better column width adjustment in DBGrid.

dan-gph
  • 16,301
  • 12
  • 61
  • 79
Tofig Hasanov
  • 3,303
  • 10
  • 51
  • 81

2 Answers2

32

You can use the Canvas.TextWidth and Canvas.TextHeight functions.

Option 1, using the canvas of the control

WidthInPixels := Label1.Canvas.TextWidth('My Text');

Option 2, creating a temporary canvas (using a Tbitmap)

Function GetWidthText(const Text:String; Font:TFont) : Integer;
var 
  LBmp: TBitmap; 
begin
  LBmp := TBitmap.Create;
  try
   LBmp.Canvas.Font := Font;
   Result := LBmp.Canvas.TextWidth(Text); 
  finally
   LBmp.Free;
  end;
end;
Ken White
  • 123,280
  • 14
  • 225
  • 444
RRUZ
  • 134,889
  • 20
  • 356
  • 483
6

if you have a Delphi component has a "Canvas" property, then you can use Component.Canvas.TextWidth. For example: to get the width of the text of DBGrid you can use:

DBGrid1.Canvas.TextWidth('Stack'); 

Here you can find complete reference about this issue: Length of Delphi string in pixels

Wael Dalloul
  • 22,172
  • 11
  • 48
  • 57