我需要在一个类库中构建一个函数,该函数接受一个字符串和一个特定的字体来计算该字符串的宽度。
那么我应该如何获取字符串的边界宽度呢?
我需要在一个类库中构建一个函数,该函数接受一个字符串和一个特定的字体来计算该字符串的宽度。
那么我应该如何获取字符串的边界宽度呢?
另一种方法是使用 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
对象,然后调用MeasureString()
方法进行测量。这是一种相当常见的GDI+技术。MeasureString
方法,现在我得到了一个类型为SizeF的返回值,然后将其转换为PointF,我现在知道宽度,但是在PointF中>>>我需要它以厘米为单位!我尝试将其转换为Postscript点,但我认为我的转换公式不正确>>那么在获取poinf宽度后如何进行转换!? - AshOoOPointF
是Point
的float
值(即非整数值)。将点转换为厘米应该是可行的(点->像素->dpi->英寸->厘米?),但是你为什么需要厘米呢? - Neil Barnwell最初的回答:
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;
}