BLOG.CSHARPHELPER.COM: Make a Label that wraps text use the largest font it can while still allowing its text to fit in C#
Make a Label that wraps text use the largest font it can while still allowing its text to fit in C#
The example Make a Label use the largest font it can while still allowing its text to fit in C# shows how you can pick a font size to make text large but still fit inside a Label. This example is similar except it allows the text to wrap in the Label.
The only change to the code is in the test that determines whether the current font size is too big. The previous example used this test:
SizeF text_size = gr.MeasureString(txt + "m", test_font, wid);
if (text_size.Height > hgt)
{
best_size = i - 1;
break;
}
The new version specifies a maximum width in the call to MeasureString so MeasureString wraps the text if it won't fit within the allowed width. The code then checks the size returned by MeasureString and moves to a smaller font size if the text is too tall. The text should not be too wide because MeasureString won't allow it to exceed the maximum width.
Download the example program or see the previous example for more details.
Comments