I want to find correct approach for calculating text width for specified font in C#.
I have following approach in Java and it seems it works:
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();
}
But watch my code in 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;
}
I have different values for above two functions for the same font. Why? And what is correct approach in my case?
UPDATE: The TextRenderer.MeasureText approach gives only integer measurements. I need more precuse result.
Use
TextRendererThere is a good article on
TextRendererin this MSDN Magazine article.