changing cynamic textsize depending on label size

Oswald

Member
Licensed User
Longtime User
changing dynamic textsize depending on label size

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.

I need your help
BX
 
Last edited:

klaus

Expert
Licensed User
Longtime User
You can do it with this routine :
B4X:
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.

Best regards.
 
Upvote 0

Oswald

Member
Licensed User
Longtime User
Hello Klaus
thank you very much for the code
I will try and comeback to you with the result

bravox
 
Upvote 0

yttrium

Active Member
Licensed User
Longtime User
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.
 
Upvote 0

yttrium

Active Member
Licensed User
Longtime User
Upvote 0

mjtaryan

Active Member
Licensed User
Longtime User
Text is set in px, and is automatically scaled for densities.

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.
 
Upvote 0

yttrium

Active Member
Licensed User
Longtime User

Sorry, upon further research you should scale text with the sp unit.
http://developer.android.com/guide/topics/resources/more-resources.html#Dimension
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…