Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# single font character size?

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.

like image 463
Bitterblue Avatar asked Oct 21 '22 19:10

Bitterblue


1 Answers

Use the MeasureString method:

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

where font is an instance of the Font class.

like image 160
Mike Perrenoud Avatar answered Nov 15 '22 05:11

Mike Perrenoud