Make a label's font as big as possible while still allowing its text to fit in C#

The following SizeLabelFont method 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.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.