Size a font to fit a Label in C#

[Size a font to fit]

The following SizeLabelFont method shows how to size a font to fit a Label‘s text. It gives a Label the biggest font possible while still allowing its text to fit.

// Copy this text into the Label using
// the biggest font that will fit.
private void SizeLabelFont(Label lbl)
{
    // Only bother if there's text.
    string txt = lbl.Text;
    if (txt.Length > 0)
    {
        int best_size = 100;

        // See how much room we have, allowing a bit
        // for the Label's internal margin.
        int wid = lbl.DisplayRectangle.Width - 3;
        int hgt = lbl.DisplayRectangle.Height - 3;

        // Make a Graphics object to measure the text.
        using (Graphics gr = lbl.CreateGraphics())
        {
            for (int i = 1; i <= 100; i++)
            {
                using (Font test_font =
                    new Font(lbl.Font.FontFamily, i))
                {
                    // See how much space the text would
                    // need, specifying a maximum width.
                    SizeF text_size =
                        gr.MeasureString(txt, test_font);
                    if ((text_size.Width > wid) ||
                        (text_size.Height > hgt))
                    {
                        best_size = i - 1;
                        break;
                    }
                }
            }
        }

        // Use that font size.
        lbl.Font = new Font(lbl.Font.FontFamily, best_size);
    }
}

The interesting part of the code starts when the program makes a Graphics object associated with the Label. The program then loops through font sizes 1 through 100. For each size, it makes a font of that size with the same font family as the Label‘s font. The code uses the Graphics object’s MeasureString method to see if the text will fit in the Label. If the text is too big, the code breaks out of the loop and uses the next smaller font size.

This is a fairly simplistic method but it works reasonably well in most circumstances.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in fonts, graphics and tagged , , , , , , , , , , . Bookmark the permalink.

5 Responses to Size a font to fit a Label in C#

  1. Curtis says:

    Wow this was really helpful thank you!!

  2. Phillip says:

    Use this to adapt for multi lines:

    SizeChanged += (sender, args) =>
        {
            if (textBox1.Text.Length > 0)
            {
                int maxSize = 100;
    
                // Make a Graphics object to measure the text.
                using (Graphics gr = textBox1.CreateGraphics())
                {
                    for (int i = 1; i < textBox1.Height)
                    {
                        maxSize = i - 1;
                        break;
                    }
                }
                catch (System.ComponentModel.Win32Exception)
                {
                    // this sometimes throws a "failure to create window handle" error.
                    // This might happen if the TextBox is invisible and/or
                    // too small to display a toolbar.
                    // do whatever here, add/delete, whatever, maybe set to default font size?
                    maxSize = (int)textBox1.Font.Size;
                }
            }
        }
    
    // Use that font size.
    textBox1.Font = new Font(textBox1.Font.FontFamily, maxSize);
  3. Jaime Stuardo says:

    It does not work for a simple label inside a cell in TableLayoutPanel.

  4. Unknown says:

    it does not work becuase some @#&*%$#*& posted the crapola

    • RodStephens says:

      I wish people would stop being total idiots. Obviously I wouldn’t post something that didn’t work. If an example isn’t working, then you’re doing something wrong.

      The two most common things people do wrong are:

      1. Not downloading the example. Most of the examples only describe the key concepts so you cannot copy and paste what’s on the web page and expect it to work. You need to download the example to see all of the details.

      2. Not unzipping the downloaded project. Visual Studio very cleverly acts as if it can open a project within a zip file but it can’t and when you try to do that it displays a meaningless error message.

      Finally, don’t be such a jerk. If you want help, just ask. Many of the examples on this site are direct replies to people who asked for help. Comments filled with obscene rants and insults won’t get you much help.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.