views:

412

answers:

2

I believe this question was already asked, but it was in Java, so I couldn't understand the solution.

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.

Thank you, Tofig Hasanov

+8  A: 

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(aText:String;aFont:TFont) : Integer;
var 
  Bmp: TBitmap; 
begin
  Bmp := TBitmap.Create;
  try
   Bmp.Canvas.Font := aFont;
   Result := Bmp.Canvas.TextWidth(aText); 
  finally
   Bmp.Free;
  end;
end;

Bye.

RRUZ
Bet me too it by 10 secs!
Gerry
+3  A: 

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