iOS Code Snippet Measure Text

SubName: MeasureText

Description:
I was itching to use NativeObject for something useful and tried and failed to measure strings using it. But then I looked at the methods available from within B4i for Views and on testing, it was possible to measure the strings without NativeObject.

These are the subs I came up with, and we don't even have to add the label to a parent for it to work.

B4X:
Sub MeasureTextHeight(Text As String,UseFont As Font,Multiline As Boolean) As Double
    Return MeasureText(Text,UseFont,Multiline)(1)
End Sub
Sub MeasureTextWidth(Text As String,UseFont As Font,Multiline As Boolean) As Double
    Return MeasureText(Text,UseFont,Multiline)(0)
End Sub
Sub MeasureText(Text As String,UseFont As Font,Multiline As Boolean) As Double()
    Dim L As Label
    L.Initialize("")
    L.Font = UseFont
    L.Text = Text
    L.Multiline = Multiline
    L.SizeToFit
    Dim Result(2) As Double
    Result(0) = L.Width
    Result(1) = L.Height
    Return Result
End Sub

Usage:
B4X:
    Dim TestStr As String
  
    TestStr = "TestTestTestTestTestTestTestTest"
  
    Log(MeasureTextWidth(TestStr,Font.DEFAULT,False))
    Log(MeasureTextHeight(TestStr,Font.DEFAULT,False))
  
    TestStr = "TestTestTestTestTestTest " & CRLF & "TestTestTestTestTestTestTestTest"
  
    Log(MeasureTextWidth(TestStr,Font.DEFAULT,True))
    Log(MeasureTextHeight(TestStr,Font.DEFAULT,True))



Tags: B4i ios Measure Text String
 
Last edited:

stevel05

Expert
Licensed User
Longtime User
Oh Oh, I have read some of the documentation, honest :D
 
Top