Defining text width

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) { // 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 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.

+4
source share
2 answers

Use TextRenderer

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

There is a good article in the MSDN journal article.

+8
source

Nothing stands out, except for the lack of disposal of 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; } 

Another method to check is the TextRenderer class:

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

but it returns an int, not a float.

+2
source

Source: https://habr.com/ru/post/1401629/


All Articles