Q. How can I determine the Length in pixels of a string after a specific font has been applied to it?
A. The two methods, TextHeigh and TextWidth, can be used to determine both the text height and width of a string in pixels. These methods can only be accessed through components that have a Canvas property such as TForm. The TPanel component does not have access to its Canvas property by default because it is protected.
If a component doesn't have a Canvas property then The following function will return the text width based on the font passed.
function GetTextWidth(CanvasOWner: TForm; Text : String; TextFont
: TFont): Integer;
var
OldFont : TFont;
begin
OldFont := TFont.Create;
try
OldFont.Assign( CanvasOWner.Font );
CanvasOWner.Font.Assign( TextFont );
Result := CanvasOWner.Canvas.TextWidth(Text);
CanvasOWner.Font.Assign( OldFont );
finally
OldFont.Free;
end;
end;