Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining text width

Tags:

java

c#

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.

like image 373
Michael Z Avatar asked Mar 15 '12 14:03

Michael Z


2 Answers

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.

like image 111
Olivier Jacot-Descombes Avatar answered Oct 13 '22 19:10

Olivier Jacot-Descombes


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.

like image 20
LarsTech Avatar answered Oct 13 '22 20:10

LarsTech