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 TextRenderer
Size size = TextRenderer.MeasureText( < with 6 overloads> );
TextRenderer.DrawText( < with 8 overloads> );
There is a good article on TextRenderer
in this MSDN Magazine article.
Nothing stands out, other than lack of disposing your objects:
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;
}
The other method to try is the TextRenderer
class:
return TextRenderer.MeasureText(text, f).Width;
but it returns an int, not a float.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With