I want to find the right approach to calculate the text width for a specified font in C #. I have the following approach in Java and it seems to work:
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 look at my C # code:
public static float TextWidth(string text, Font f) {
I have different values ββfor two functions for the same font. What for? And what is the right approach in my case?
UPDATE The TextRenderer.MeasureText approach gives only integer dimensions. I need more preventive results.
source share