Dotnet: How do you get the average character width for a font?

Windows Forms:

For System.Drawingthere is a way to get the font height.

Font font = new Font("Arial", 10 , FontStyle.Regular);
float fontHeight = font.GetHeight(); 

But how do you get other textual metrics like average character width?

+5
source share
5 answers

Use the Graphics.MeasureString Method

private void MeasureStringMin(PaintEventArgs e)
{

    // 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);

    // Draw rectangle representing size of string.
    e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);

    // Draw string to screen.
    e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
}
+4
source

There is no strictly average font width, since kerning can have an effect depending on what letters are before and after any letter.

If you want to use the non-fixed-size fonts used in the fixed-width script, your main option is to whiten the characters across the width of the uppercase “W” character.

, , , - :

StringBuilder sb = new StringBuilder();

// Using the typical printable range
for(char i=32;i<127;i++)
{
    sb.Append(i);
} 

string printableChars = sb.ToString();

// Choose your font
Font stringFont = new Font("Arial", 16);

// Now pass printableChars into MeasureString
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(printableChars, stringFont);

// Work out average width of printable characters
double average = stringSize.Width / (double) printableChars.Length;
+4

, . - , "i" "l", , ASCII .

+2

.

,

+1

.NET. Graphics.MeasureString TextRenderer.MeasureString.

+1
source

All Articles