Get System.Drawing.Font width?

2019-05-01 11:56发布

问题:

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?

回答1:

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();
    stringSize = e.Graphics.MeasureString(measureString, stringFont);
    // This will give you string width, from which you can calculate further 
    double width = stringSize.Width


回答2:

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.