Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get System.Drawing.Font width?

I'm using .Net tools to do some 2D drawing. System.Drawing.Font uses a GetHeight() that returns the height in pixels. I'm missing a GetWidth() to retrieve the width! What should I use?

like image 605
Kees C. Bakker Avatar asked Nov 07 '12 11:11

Kees C. Bakker


2 Answers

Use Graphics.MeasureString Method (String, Font):

Eg.

   // Set up string. string measureString = "Measure String";
    Font stringFont = new Font("Arial", 16);
    // Measure string.
    SizeF stringSize = new SizeF();
    Graphics gfx = Graphics.FromImage(new Bitmap(1, 1));
    stringSize = gfx.MeasureString(measureString, stringFont);
    // This will give you string width, from which you can calculate further 
    double width = stringSize.Width
like image 135
Kapil Khandelwal Avatar answered Nov 07 '22 19:11

Kapil Khandelwal


What width? GetHeight returns the distance between the baselines of two lines of text, which is a property of the font itself. But the width depends on what you're going to write.

If you know what it is you want to write, try the Graphics.MeasureString methods.

like image 4
Rawling Avatar answered Nov 07 '22 19:11

Rawling