Get the width in pixels of any given character

I have this awesome idea, but I can’t find out if there are any classes in the .NET Framework (any version, preferably 3.5 or 4.0) that allow the character to be transferred and the width returned in pixels, no matter what font, font size or decoration font used. Can someone point me in the right direction? Is there a class / something else for something like that?

+7
source share
2 answers

Check out the Graphics.MeasureString method .

Sample code adapted from the link:

SizeF charSize = e.Graphics.MeasureString("X", new Font("Arial", 16)); // do stuff with charSize ... 

The above example assumes that you are in the body of the Paint event handler function and the Graphics object has already been created for you and passed as an event parameter. If you do not want or cannot do this in the Paint handler, you can create a graphic object of your choice using Control.CreateGraphics .

+5
source

If WPF works for you (I see that someone just removed the WPF tag for this question, but it was there initially), there is also FormattedText :

 FormattedText formattedText = new FormattedText("hello foo", CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Arial"), FontSize = 14, Brushes.Black); double width = formattedText.Width; 
+4
source

All Articles