I have forms with fixed sized labels that will have variable length text values set to them and I want to be able to calculate the maximum font size possible to make the text fill the label control without loosing any characters. (Note I do NOT want to resize the label to fit the text)
The labels have their AutoSize and UseMnemonic properties set to False and the text must be allowed to flow onto multiple lines as to fill the width and height of the control as much as possible.
So a typical label size could be 700 wide by 300 high and the output should look something like this:
Which groups’s
best-selling album was
titled Hi Infidelity
This is the best code I have to date which fits the brief most of the time however short single words like “2019” sometimes have the last character missing and some single longer words like for example ‘Mississippi’ calculate the font size to small. (Think this may have something to do with the number of letter ‘i’s.
Also phrases like “Hollywood & Vine” and “What is Homer’s long-lost brother’s name?” also
do not fit correctly.
So I’m guessing MeasureString is not calculating correctly or this isn’t the correct approach.
Dim best_size As Integer = 6
Dim wid As Integer = mylabel.ClientSize.Width - mylabel.Padding.Left - mylabel.Padding.Right - mylabel.Margin.Left - mylabel.Margin.Right
Dim hgt As Integer = mylabel.ClientSize.Height - mylabel.Padding.Top - mylabel.Padding.Bottom - mylabel.Margin.Top - mylabel.Margin.Bottom
Using gr As Graphics = mylabel.CreateGraphics()
For i As Integer = 6 To 1000 Step 1
Using test_font As New Font(mylabel.Font.FontFamily, i, mylabel.Font.Style)
Dim text_size As SizeF = gr.MeasureString(mylabel.Text, test_font, mylabel.ClientSize, StringFormat.GenericDefault)
If wid >= hgt Then
'short(height) and wide(width) so break on height
If text_size.Height >= hgt Then
best_size = i
Exit For
End If
Else
'tall(height) and narrow(width) so break on width
If text_size.Width >= wid Then
best_size = i
Exit For
End If
End If
End Using
Next i
End Using
'This shouldn't be required but I needed some adjustment as the calculated font size is always to big.
best_size = best_size * 0.8
mylabel.Font = New Font(mylabel.Font.FontFamily, best_size, mylabel.Font.Style)
Obviously using a loop like this is not ideal but after trying a ratio calculation I loose the multi line requirement.
Does anyone have any ideas what could be changed to make this calculate the best font size for the label rectangle without it loosing characters yet making it fill the control while still allowing multiline text?