Android Question B4XCanvas.MeasureText for CharSequence

Toky Olivier

Active Member
Licensed User
Longtime User
Hi all,
I wanted to fit long text in a label but it seems that CharSequences don't work well with the B4XCanvas MeasureText. I think that the cause is the use of different fonts in the text. Is there another method to do so?

Here is my code:
B4X:
Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("1")
    FitTextInLabel(Label1,"One very long text in Android")
    Label3.Text = Label1.Text
    
    Dim cs As CSBuilder
    cs.Initialize.Color(Colors.Green).Typeface(Typeface.FONTAWESOME).Append(Chr(0xF17B)).PopAll.Append(" One very long text in Android")
    FitTextInLabel(Label2,cs)
    Label4.Text = cs
End Sub

Private Sub FitTextInLabel(lbl As Label, txt As Object)
    Private dt As Float
    Private limit = 0.5 As Float
    Private stp = 0.5 As Float
    Private cnv As B4XCanvas
    Dim mylbl As B4XView = lbl
    cnv.Initialize(lbl)
    Dim r As B4XRect = cnv.MeasureText(txt, mylbl.Font)
    Dim w As Float = r.Width
    dt = mylbl.Font.Size
    Do While (dt > limit Or w > mylbl.Width)
        dt = dt / 2
        r = cnv.MeasureText(txt, mylbl.Font)
        w = r.Width
        If w > mylbl.Width Then
            mylbl.TextSize = mylbl.TextSize - stp
        End If
    Loop
    lbl.Text = txt
End Sub

Thank you
 

Attachments

  • Screenshot_1560591755.png
    Screenshot_1560591755.png
    12 KB · Views: 249
  • FitTextInLabel.zip
    9.3 KB · Views: 230

Toky Olivier

Active Member
Licensed User
Longtime User
Thank you Erel. What do you mean:
Create the canvas once with a 1x1 mutable bitmap
please?
I should declare the B4XCanvas object in the Process Global section, initialize it in the Activity_Create sub for example and reuse it in the function FitTextInLabel?
I tested the new BBCodeView but It hasn't the function to adjust the font size. Or I'm wrong?
Thank you again.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
I should declare the B4XCanvas object in the Process Global section, initialize it in the Activity_Create sub for example and reuse it in the function FitTextInLabel?
Almost. It should be in Globals as it holds an activity context.

I tested the new BBCodeView but It hasn't the function to adjust the font size. Or I'm wrong?
It can measure rich text. It will require some work.
 
Upvote 0
Top