6

Windows Forms:

For System.Drawing there 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 the other text metrics like average character width?

Ray Hayes
  • 14,896
  • 8
  • 53
  • 78
P a u l
  • 7,805
  • 15
  • 59
  • 92

4 Answers4

4

Use 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));
}
Ramesh Soni
  • 15,867
  • 28
  • 93
  • 113
4

There isn't strictly an average width for fonts as kerning can have an effect depending upon what letters are before and after any given letter.

If you want to non-fixed sized fonts used in a fixed-width scenario, your main option is to space the characters by the width of the upper case "W" character.

Others have already given an example of getting the width of a specified string, but to answer your question, to get a true average of printable characters you might want to do something like:

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;
Ray Hayes
  • 14,896
  • 8
  • 53
  • 78
3

Tricky, as you should use the character frequency as well. If you've ever seen Finnish, with all its "i"s and "l"s, you will realize that even a pure ASCII font has no welldefined average character width.

MSalters
  • 173,980
  • 10
  • 155
  • 350
1

I've never seen an average character width property in .NET. You can get the width of a particular string in a particular font by using Graphics.MeasureString or TextRenderer.MeasureString.

MusiGenesis
  • 74,184
  • 40
  • 190
  • 334