我希望找到在C#中计算指定字体文本宽度的正确方法。以下是我在Java中使用的方法,似乎可以工作:
public static float textWidth(String text, Font font) {
// define context used for determining glyph metrics.
BufferedImage bufImage = new BufferedImage(2 /* dummy */, 2 /* dummy */, BufferedImage.TYPE_4BYTE_ABGR_PRE);
Graphics2D g2d = (Graphics2D) bufImage.createGraphics();
FontRenderContext fontRenderContext = g2d.getFontRenderContext();
// determine width
Rectangle2D bounds = font.createGlyphVector(fontRenderContext, text).getLogicalBounds();
return (float) bounds.getWidth();
}
但是请看我的C#代码:
public static float TextWidth(string text, Font f)
{
// define context used for determining glyph metrics.
Bitmap bitmap = new Bitmap(1, 1);
Graphics grfx = Graphics.FromImage(bitmap);
// determine width
SizeF bounds = grfx.MeasureString(text, f);
return bounds.Width;
}
对于相同的字体,以上两个函数给出不同的值。为什么呢?在我的情况下,正确的方法是什么?
更新:使用 TextRenderer.MeasureText 方法只能得到整数测量值。我需要更精确的结果。