How to figure out the pixel width of a string with a given Font

Is there a way to figure out how many x-pixels a string has within a given Font? This problem occurs if I am using proportional fonts.
klusiAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
intheConnect With a Mentor Commented:
hi,
i paste this from the delphi help file:

function TextWidth(const Text: string): Integer;
 
Description
The TextWidth method returns the width in pixels of the string passed in Text when rendered in the current font. You can use TextWidth to determine whether a given string will fit in a particular space.
 
example:

procedure TForm1.Button1Click(Sender: TObject);
var
i : integer;
begin
i := label1.Canvas.textwidth('some string');
showmessage(inttostr(i));
end;

Regards Barry
0
 
DrDelphiCommented:
Look at the GetTextMetric API.
0
 
DrDelphiCommented:
Sorry, I have to amend myself.... you'd probably fare better with GetTextExtentPoint32  since you know what your string is already. GetTextMetrics is useful for calculating what a string's length would be given the fonts used, etc...


Good luck!!
0
 
DrDelphiCommented:
Quick sample:

var size:TSize;
begin
  Form1.Canvas.textout(0,0,'Dave was here');
  GetTextExtentPoint32(Form1.canvas.handle,'Dave was here',length('Dave was here'),size);
  form1.canvas.brush.style:=BsClear;
  form1.canvas.rectangle(0,0,size.cx,size.cy);
end;



Good luck!!
0
 
hubdogCommented:
look into the source of canvas.textwidth
it uses GetTextExtentPoint32 api to get the string width.

so i think canvas.textwidth more easy than GetTextExtentPoint32

happy new year!
0
All Courses

From novice to tech pro — start learning today.