Make a Label use the largest font it can while still allowing its text to fit in C#

When you change the text in the program's TextBox, the following code executes to display the text as large as possible in the Label above.

// Copy this text into the Label using
// the biggest font that will fit. private void txtSample_TextChanged(
object sender, EventArgs e) { string txt = txtSample.Text; // Only bother if there's 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 = lblSample.DisplayRectangle.Width - 3; int hgt = lblSample.DisplayRectangle.Height - 3; // Make a Graphics object to measure the text. using (Graphics gr = lblSample.CreateGraphics()) { for (int i = 10; i < 100; i++) { using (Font test_font = new Font(lblSample.Font.FontFamily, i)) { // See how much space the text would need, // specifying a maximum width. SizeF text_size = gr.MeasureString(txt + "m", test_font); if ((text_size.Width > wid) || (text_size.Height > hgt)) { best_size = i - 1; break; } } } } // Use that font size. lblSample.Font = new Font(lblSample.Font.FontFamily, best_size); } // Display the text. lblSample.Text = txt; }

The code creates a Graphics object and then creates a series of fonts in increasingly larger sizes. It uses the Graphics object's MeasureString method to see if the text will fit in the Label. When it finds a font size that's too big, it stops and uses the previous font size.

The code adds an "m" character when measuring the string to give it a little extra room. If you omit that, then the text sometimes doesn't quite fit. Adding the "m" and using only integral font sizes makes this method somewhat approximate but it should prove useful.

The Label control seems to cheat when it's Font is set to a small font (under around 9 point). Then it seems to use a font different from the one that is used by a Graphics object drawing the same text with the same font. That makes the code fail to correctly measure the text as it would be drawn by the Label.

To prevent this problem, the code doesn't use fonts smaller than 9 point so it won't work for too much text in a small label.

   

 

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.