Hi all...
The basis of the code below was posted by Klaus, quite a while ago. It's purpose is to dynamically size text for a multi-line label. I've screwed around with it a lot, primarily because the first iteration Klaus posted worked sometimes, not others. In some cases, the last line of the text was below the visible label space, and sometimes, only a portion of the text is displayed. I also put in some code to detect Carriage Returns and Line Feeds (CRLFs) because they definitely threw it off too.
The label sizes vary quite a bit based upon device, so they're resized when needed.
I really need this code to work, and I've messed with it and stared at it for so long now that I've lost objectivity. The idea is to pass changing text to a label, the size of which may have changed via orientation change, and the text has to fit and be completely shown. Any help would be really appreciated... I have tried different starting font sizes, to no avail. I'm stuck.
The basis of the code below was posted by Klaus, quite a while ago. It's purpose is to dynamically size text for a multi-line label. I've screwed around with it a lot, primarily because the first iteration Klaus posted worked sometimes, not others. In some cases, the last line of the text was below the visible label space, and sometimes, only a portion of the text is displayed. I also put in some code to detect Carriage Returns and Line Feeds (CRLFs) because they definitely threw it off too.
The label sizes vary quite a bit based upon device, so they're resized when needed.
I really need this code to work, and I've messed with it and stared at it for so long now that I've lost objectivity. The idea is to pass changing text to a label, the size of which may have changed via orientation change, and the text has to fit and be completely shown. Any help would be really appreciated... I have tried different starting font sizes, to no avail. I'm stuck.
B4X:
Sub SetTextSize(lbl As Label, txt As String)
Dim dt As Float
Dim limit = 1 As Float
Dim h As Int
'This loop determines how many CRLFs there are in the text.
Dim charcnt As Double
Dim x2, placer, placerct, ts As Int
For x = 0 To txt.Length -1
placerct = 0
charcnt = txt.Length
For x2 = 0 To charcnt
placer = txt.IndexOf2(Chr(10),x2)
If placer = -1 Then
Exit
Else
placerct = placerct + 1
x2 = placer
End If
Next
Next
If placerct > 0 Then
ts = 19 - (placerct * 2)
Else
ts = 24
End If
'Now, do the resizing:
lbl.Text = txt
lbl.TextSize = ts
dt = lbl.TextSize
h = stu.MeasureMultilineTextHeight(lbl, txt)
Do While dt > limit OR h > lbl.Height
dt = dt / 2.25
h = stu.MeasureMultilineTextHeight(lbl, txt)
If h > lbl.Height Then
lbl.TextSize = lbl.TextSize - dt
Else
lbl.TextSize = lbl.TextSize + dt
End If
Loop
End Sub