Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining the Width in Pixels of any given character

I have this really awesome idea, but cannot find out if there are any classes in the .NET Framework (any version, preferrably 3.5 or 4.0) that allow you to pass in a character, and get back the width in pixels of that character, no matter which font, or font size or font-decoration is being used. Can someone please point me in the right direction? Does a class/something even exist for something like this?

like image 916
βӔḺṪẶⱫŌŔ Avatar asked Apr 08 '11 03:04

βӔḺṪẶⱫŌŔ


1 Answers

Check out the Graphics.MeasureString method.

Code sample adapted from the link:

SizeF charSize = e.Graphics.MeasureString("X", new Font("Arial", 16));
// do stuff with charSize ...

The sample above assumes you're in the function body of a Paint event handler and the Graphics object is already created for you and passed in as an event parameter. If you don't want or can't do it in a Paint handler you can create a graphics object at your convenience with Control.CreateGraphics.

like image 198
Paul Sasik Avatar answered Oct 01 '22 19:10

Paul Sasik