Wish B4X XUI Add MeasureTextWidth and MeasureTextHeight to B4XCanvas

klaus

Expert
Licensed User
Hi Erel,
The title says the wish.
Currently, there are three different routines in the class with different results.
Example:
MeasureTextHeight("Mg") and MeasureTextHeight("M") give different results in B4A because the real height is different, but give the same result in B4J.
I have not checked with B4i.
 

klaus

Expert
Licensed User
I use this code in the xChart class:
B4X:
Private Sub MeasureTextWidth(Text As String, Font1 As B4XFont) As Int
#If B4A
    Private bmp As Bitmap
    bmp.InitializeMutable(2dip, 2dip)
    Private cvs As Canvas
    cvs.Initialize2(bmp)
    Return cvs.MeasureStringWidth(Text, Font1.ToNativeFont, Font1.Size)
#Else If B4i
    Return Text.MeasureWidth(Font1.ToNativeFont)
#Else If B4J
    Dim jo As JavaObject
    jo.InitializeNewInstance("javafx.scene.text.Text", Array(Text))
    jo.RunMethod("setFont",Array(Font1.ToNativeFont))
    jo.RunMethod("setLineSpacing",Array(0.0))
    jo.RunMethod("setWrappingWidth",Array(0.0))
    Dim Bounds As JavaObject = jo.RunMethod("getLayoutBounds",Null)
    Return Bounds.RunMethod("getWidth",Null)
#End If
End Sub

Private Sub MeasureTextHeight(Text As String, Font1 As B4XFont) As Int
#If B4A    
    Private bmp As Bitmap
    bmp.InitializeMutable(2dip, 2dip)
    Private cvs As Canvas
    cvs.Initialize2(bmp)
    Return cvs.MeasureStringHeight(Text, Font1.ToNativeFont, Font1.Size)
#Else If B4i
    Return Text.MeasureHeight(Font1.ToNativeFont)
#Else If B4J
    Dim jo As JavaObject
    jo.InitializeNewInstance("javafx.scene.text.Text", Array(Text))
    jo.RunMethod("setFont",Array(Font1.ToNativeFont))
    jo.RunMethod("setLineSpacing",Array(0.0))
    jo.RunMethod("setWrappingWidth",Array(0.0))
    Dim Bounds As JavaObject = jo.RunMethod("getLayoutBounds",Null)
    Return Bounds.RunMethod("getHeight",Null)
#End If
End Sub
I had found the code for B4J in the forum.
Looking closer on the B4J code, I think I understand why the heights are the same.
There is probably another method to get the height.
 
Last edited:

klaus

Expert
Licensed User
Hi Erel,
The main reason of this thread is the wish to add MeasureTextWidth and MeasureTextHeight methods to the B4XCanvas object.
I mentioned the height differences as an information, the code in post #3 works for what I need in the xChart class.
The wish is to have method directly in B4XCanvas instead of three routines in the class.

Returns the same value as the code in post #3.

Log(MeasureMultilineTextHeight(mFont, 100, "Mg"))
Log(MeasureMultilineTextHeight(mFont, 100, "M"))
Log(MeasureTextHeight("Mg", mFont))
Log(MeasureTextHeight("M", mFont))


All four Logs give the same value
 
Top