5

This is not about the size of a string.

I specify a font for drawing strings. And now I need the exact width of 1 character in pixels. I only allow fonts that have static char-width (W and i have the same width when drawn). If I use "Consolas" with size of 10 I get an estimated width of 7.75f. Can I retrieve this information directly somehow ?

I don't need this information while drawing but when I want to set cursor position etc. So I don't know what text is beneath cursor.

Edit: MeasureString gives me 11.99653 as char width. Dunno why. But I can't use this value. I estimated 7.75f and it's pretty exact. I'll get in trouble if I want to change font size.

Bitterblue
  • 13,162
  • 17
  • 86
  • 124
  • 3
    The inaccuracy of `MeasureString` is discussed [here](http://stackoverflow.com/questions/118686/measurestring-pads-the-text-on-the-left-and-the-right), [here](http://stackoverflow.com/questions/3811916/measurestring-and-drawstring-difference) and [here](http://social.msdn.microsoft.com/Forums/en-US/0d991394-4911-42b8-8cb5-7cd3c745c87b/graphicsmeasurestring-is-not-accurate). – O. R. Mapper Dec 02 '13 at 13:28
  • 2
    You cannot make this work, pretty fundamental about the way Windows renders text. It alters the letter shape, stretching it as necessary to make the stems in a letter coincide with the pixel grid. This produces highly readable text but highly unpredictable widths. True resolution independent text rendering was never accurate enough in GDI+. And tried again in WPF and universally panned for lousy readability. Fixed in .NET 4.0 by adding the distinction between Display and Ideal rendering modes. Only ever measure complete strings, never individual letters. – Hans Passant Dec 02 '13 at 13:58

1 Answers1

3

Use the MeasureString method:

Graphics g = this.CreateGraphics();
g.MeasureString("A", font, 10, StringFormat.GenericTypographic);

where font is an instance of the Font class.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232