Calculate the display width of a string in C#?

C#.Net

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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...

Solution 3 - C#

Solution 4 - C#

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

Solution 5 - C#

You would use Graphics.MeasureString.

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

Solution 6 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeffrey MeyerView Question on Stackoverflow
Solution 1 - C#AlanView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#Todd WhiteView Answer on Stackoverflow
Solution 4 - C#Andrew BullockView Answer on Stackoverflow
Solution 5 - C#jons911View Answer on Stackoverflow
Solution 6 - C#Thulani ChivandikwaView Answer on Stackoverflow