Hello,
Size of the label (vertically and horizontally) is static, fixed.
But the text is dynamic, depending of the text length I need to change the textsize to fit it in to the label, with the the maximum textsize.
Sub SetLabelTextSize(lbl As Label, txt As String, MaxFontSize As Float, MinFontSize As Float)
Dim FontSize = MaxFontSize As Float
Dim Height As Int
Dim stu As StringUtils
lbl.TextSize = FontSize
Height = stu.MeasureMultilineTextHeight(lbl, txt)
Do While Height > lbl.Height AND FontSize > MinFontSize
FontSize = FontSize - 1
lbl.TextSize = FontSize
Height = stu.MeasureMultilineTextHeight(lbl, txt)
Loop
End Sub
It needs the StringUtils library.
MaxFontSize allows to limit the number of iterations.
MinFontSize allows to limit the minimum font size.
You can also omit one or both parameters and work with fixed values insides the routine.
You can also do this as follows each time you change the text:
B4X:
Label1.TextSize = Label1.Height * 800/1000dip
The following makes the TextSize 80% of the height (800 out of 1000).
Using this formula you can be accurate down to the first decimal place of a percentage.
For example, 75.2% of the height would be:
B4X:
Label1.TextSize = Label1.Height * 752/1000dip
Anywhere between 75% and 85% looks good for a single line.
The only issue with this is that you can't factor in the length of text, and wrapping - you'd have to hardcode these values. For more dynamic usage, use what klaus described.
Unfortunately, the automatic scaling is not 100% accurate. In testing some of my apps on different devices with different densities, with some densities the scaled text size exceeds the height and width of the scaled label or button. I'm wondering if text size in pts might scale better? Not being a typographer, I have no way of knowing. But this anomaly makes both methods provided here useful.
Unfortunately, the automatic scaling is not 100% accurate. In testing some of my apps on different devices with different densities, with some densities the scaled text size exceeds the height and width of the scaled label or button. I'm wondering if text size in pts might scale better? Not being a typographer, I have no way of knowing. But this anomaly makes both methods provided here useful.