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