Mirror

How to get the text width in pixels when a component doesn't have a canvas (Views: 100)


Problem/Question/Abstract:

How to get the text width in pixels when a component doesn't have a canvas

Answer:

If a component doesn't have a Canvas property you can use the following function to get 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;

<< Back to main page