61

A Java version of this question was just answered, and, well, I don't know how to do this in .net.

So how do you calculate the display width of a string in C# / .net?

6 Answers 6

68

An alternative for Windows Forms is the static TextRenderer.MeasureText method.

Although restricted to integer sizes, this (in tandem with TextRenderer.DrawText) renders more accurate and much higher quality ClearType text than the Graphics.MeasureString/DrawString duo.

Sign up to request clarification or add additional context in comments.

1 Comment

See this thread: stackoverflow.com/questions/6704923/… and this blog post: blogs.msdn.com/b/jfoscoding/archive/2005/10/13/480632.aspx for more information. It would seem that use of TextRenderer.MeasureText is the method applicable to most usage of .Net WinForms.
62

You've got the same problem in this question as was present in the Java question - not enough information! It will differ between WinForms and WPF.

For WinForms: Graphics.MeasureString

For WPF I'm not sure, but I suspect it will depend on the exact way you're drawing the text...

6 Comments

In WPF you would use FormattedText, msdn.microsoft.com/en-us/library/….
How would you do that in ASP.NET?
@Shimmy: Well in ASP.NET it will entirely depend on what the browser does. It's really not the sort of thing you'd try to do in a web app - you'd use CSS to control the formatting instead.
@JonSkeet It doesn't have to be accurate, I just need to create a function that makes up a summary of a long file name so truncating it and leaving the extension i.e. msdfjkasdfjhkjhadf...pdf
@Shimmy: It's not a matter of accuracy - it's a matter of it being basically impossible to predict from the server side. You'd need to do it on the client side if anywhere. But anyway, it's definitely not a .NET question. I suggest you ask a new question, giving your requirements very precisely.
|
24

In WPF you would use FormattedText.

1 Comment

text in upper case not measured properly .
9

Graphics.MeasureString but its a bit crappy, as is explained and improved upon; here

Comments

4

You would use Graphics.MeasureString.

http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx

1 Comment

WinForms controls expose a CreateGraphics method that can be used to create the Graphics object in the first place (its constructor is private)
1

Graphics.MeasureString([text to measure],[font being used to measure text]);

The resulting object will provide the following:

properties available

Other overloads of MeasureString also available.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.