|Title||Make a Label use the largest font it can while still allowing its text to fit in Visual Basic .NET|
|Description||This example shows how to make a Label use the largest font it can while still allowing its text to fit in Visual Basic .NET.|
|Keywords||font, biggest font, largest font, Label, Visual Basic .NET, VB.NET|
|Categories||Graphics, Controls, VB.NET|
When you change the text in the program's TextBox, the following code executes. It first creates a Graphics object. It then creates a series of fonts in increasingly larger sizes and 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.
' Copy this text into the Label using hte biggest font that
' will fit.
Private Sub txtSample_TextChanged(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
Dim txt As String = txtSample.Text
' Only bother if there's text.
If txt.Length > 0 Then
Dim best_size As Integer = 100
' See how much room we have, allowing a bit
' for the Label's internal margin.
Dim wid As Integer = _
lblSample.DisplayRectangle.Width - 3
Dim hgt As Integer = _
lblSample.DisplayRectangle.Height - 3
' Make a Graphics object to measure the text.
Using gr As Graphics = lblSample.CreateGraphics()
For i As Integer = 10 To 100
Using test_font As New _
' See how much space the text would
' specifying a maximum width.
Dim text_size As SizeF = _
txt & "m", test_font)
If text_size.Width > wid OrElse _
text_size.Height > hgt Then
best_size = i - 1
' Use that font size.
lblSample.Font = New _
' Display the text.
lblSample.Text = txt
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 thue 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.