Mario M Mario M - 1 year ago 150
C# Question

Auto Resize Font to fit rectangle

How can I create in .NET 4.5 / C# a font with a adaptive size to fit a specified rectangle ?

I have a resize based on the string length, the longer the string, the smaller the fontsize, but it does not work very well, if the string is too long the text gets very small. The problem with this method is that if I change the rectangle size all the font sizes are not good again.

Answer Source

With Graphics.MeasureString you can measure the size of a string, so you can calculate what you need.

Sample from MSDN

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