# 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.
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
Look at the GetTextMetric API.
0
Commented:
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
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

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Commented:
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
Commented:
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
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Fonts Typography

From novice to tech pro — start learning today.