正在确定文本宽度

本文关键字:文本 | 更新日期: 2023-09-27 18:27:50

我想找到正确的方法来计算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;
}

对于相同的字体,上面两个函数的值不同。为什么?在我的情况下,什么是正确的方法?

UPDATETextRenderer.MeasureText方法只提供integer测量值。我需要更多的预测结果。

正在确定文本宽度

使用TextRenderer

Size size = TextRenderer.MeasureText( < with 6 overloads> );
TextRenderer.DrawText( < with 8 overloads> );

MSDN杂志的这篇文章中有一篇关于TextRenderer的好文章。

除了不处理对象之外,没有什么特别的:

public static float TextWidth(string text, Font f) {
  float textWidth = 0;
  using (Bitmap bmp = new Bitmap(1,1))
  using (Graphics g = Graphics.FromImage(bmp)) {
    textWidth = g.MeasureString(text, f).Width;
  }
  return textWidth;
}

另一种尝试的方法是TextRenderer类:

return TextRenderer.MeasureText(text, f).Width;

但它返回的是int,而不是float。