Android Question "MeasureStringWidth" gives incorrect values with density = 233

Petrus

Member
Licensed User
Longtime User
I have a device with Density = 233 (LG Optimus L5 II (E460)). MeasureStringWidth gives incorrect values:
B4X:
    'Sample text:
    Text = "This is only a sample text. This is only a sample text. This is only a sample text."
   
    'Text width:
    Dim TextWidth As Float
    TextWidth = CanvasCalc.MeasureStringWidth(Text, Typeface.DEFAULT, TSize)
    ImgL.Left = TextWidth
   
    '1.) Variant with Label:
    Label1.Text = Text
   
    '2.) Variant with DrawText: (with a string)
    Dim C As Canvas
    C.Initialize(Panel1)
    C.DrawText(Text, 0, 30, Typeface.DEFAULT, TSize, Colors.Black, "LEFT")
    Panel1.Invalidate
   
    '3.) Variant with DrawText: (split string)
    Dim C As Canvas
    C.Initialize(Panel2)
    Dim t() As String, x As Float
    t = Regex.Split(" ", Text)
    For i = 0 To t.Length -1
        C.DrawText(t(i) & " ", x, 30, Typeface.DEFAULT, TSize, Colors.Black, "LEFT")
        x = x + C.MeasureStringWidth(t(i) & " ", Typeface.DEFAULT, TSize)
    Next
    Panel2.Invalidate


Result:
Screenshot.png


With small font, the text is smaller than calculated. With large font, the text is wider than calculated. In the example gives variant 2 and 3 different widths.

Is there a solution to the problem?

regards
Petrus
 

Petrus

Member
Licensed User
Longtime User
The purple lin x-position is the calculated width (variable "TextWidth") - the line is a ImageView with width = 1.

With the AutoTextSizeLabel the problem also:

Screenshot02.png


regards
Petrus
 
Last edited:
Upvote 0
Top