Reputation: 1296
I have this really awesome idea, but cannot find out if there are any classes in the .NET Framework (any version, preferrably 3.5 or 4.0) that allow you to pass in a character, and get back the width in pixels of that character, no matter which font, or font size or font-decoration is being used. Can someone please point me in the right direction? Does a class/something even exist for something like this?
Upvotes: 8
Views: 5511
Reputation: 161002
If WPF works for you (I see someone just removed the WPF tag for this question, but it was there originally) 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;
Upvotes: 4
Reputation: 81557
Check out the Graphics.MeasureString method.
Code sample adapted from the link:
SizeF charSize = e.Graphics.MeasureString("X", new Font("Arial", 16));
// do stuff with charSize ...
The sample above assumes you're in the function body of a Paint event handler and the Graphics object is already created for you and passed in as an event parameter. If you don't want or can't do it in a Paint handler you can create a graphics object at your convenience with Control.CreateGraphics.
Upvotes: 5