如何获得字符串宽度

Ash*_*OoO 10 c# string

我需要在类库中构建一个函数,该函数接受字符串和该字符串的特定字体,然后获取字符串的宽度

那我怎么能得到字符串边界宽度?

Jos*_*ell 15

另一种方法是使用a TextRenderer,并调用 MeasureString方法,传递字符串和字体类型.

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);  
}
Run Code Online (Sandbox Code Playgroud)

注意:这只是@Neil Barnwell已经发布的(同样有效)的替代解决方案(如果您已经在项目中引用了System.Windows.Forms,这可能更方便).


Nei*_*ell 13

您可以获取一个Graphics对象(在您想要文本的容器上使用Control.CreateGraphics())并调用MeasureString()以执行此操作.这是一种相当常见的GDI +技术.

来自MSDN的更多信息:http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx

  • “PointF”只是“Point”的“浮点”值(即非整数值)。从点转换为厘米应该是可行的(点->像素->dpi->英寸->厘米?)但是为什么需要厘米? (2认同)