Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the display width of a string in C#?

Tags:

c#

.net

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.


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


In WPF you would use FormattedText.


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


You would use Graphics.MeasureString.

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


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.