如何得到一个字符串宽度 [英] How to get a string width
问题描述
我需要建立一个类库,一个字符串并将此字符串特定字体功能则得到字符串的宽度
I need to build a function in a class library that take a string and a specific font for this string then get the width of the string
所以,我怎么会得到字符串边界宽度?
So how could I get the string boundary width ?
推荐答案
另一种方式做,这是一个 TextRenderer
,并调用的及其的 MeasureString
方法,传递字符串和字体类型
Another way to do this is with a TextRenderer
, and call its MeasureString
method, passing the string and the font type.
MSDN示例:
private void MeasureText1(PaintEventArgs e)
{
String text1 = "Measure this text";
Font arialBold = new Font("Arial", 12.0F);
Size textSize = TextRenderer.MeasureText(text1, arialBold);
TextRenderer.DrawText(e.Graphics, text1, arialBold,
new Rectangle(new Point(10, 10), textSize), Color.Red);
}
注意:这仅仅是一个替代的解决方案的(同样有效)已经发表@Neil巴恩韦尔
(如果你已经在你的项目中,这可能是更方便的System.Windows.Forms的引用)之一。
NOTE: This is just an alternate solution to the (equally valid) one already posted by @Neil Barnwell (in case you already have a reference to System.Windows.Forms in your project, this might be more convenient).
这篇关于如何得到一个字符串宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!