P a u l
P a u l

Reputation: 7921

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

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?

Upvotes: 6

Views: 14274

Answers (4)

Ray Hayes
Ray Hayes

Reputation: 15015

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;

Upvotes: 4

MSalters
MSalters

Reputation: 180295

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.

Upvotes: 4

MusiGenesis
MusiGenesis

Reputation: 75396

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.

Upvotes: 2

Ramesh Soni
Ramesh Soni

Reputation: 16077

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

Upvotes: 4

Related Questions