[英]How to get a string width
我需要在类库中构建一个函数,该函数接受字符串和该字符串的特定字体,然后获取字符串的宽度
那我怎么能得到字符串边界宽度?
另一种方法是使用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);
}
注意:这只是@Neil Barnwell已经发布的(同样有效)的替代解决方案(如果您已经在项目中引用了System.Windows.Forms,这可能更方便)。
您可以获取一个Graphics
对象(在您想要文本的容器上使用Control.CreateGraphics() )并调用MeasureString()
来执行此操作。 这是一种相当常见的GDI +技术。
来自MSDN的更多信息: http : //msdn.microsoft.com/en-us/library/6xe5hazb.aspx
你可以用这个:
private float getTextSize(string text)
{
Font font = new Font("Courier New", 10.0F);
Image fakeImage = new Bitmap(1, 1);
Graphics graphics = Graphics.FromImage(fakeImage);
SizeF size = graphics.MeasureString(text, font);
return size.Width;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.