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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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.
回答2:
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;