B4J Question How to Know the Paddings of the Text in a Snapshot of Text Node

xulihang

Active Member
Licensed User
Longtime User
B4X:
Dim tf As TextFlow
tf.Initialize
tf.AddText(textToDraw)
tf.SetFont(fx.DefaultFont(32))
Dim p As Pane = tf.CreateTextFlow
Dim img As Image = p.Snapshot2(fx.Colors.White)

I am trying to take snapshots of TextFlow to get the image of text. But it has paddings:




How do I know the values of the paddings so that I can crop the image to make the text take up the entire image?

Using B4XCanvas's measureText method seems a solution but I am not sure if it is the correct way.

B4X:
Dim cvs As B4XCanvas
cvs.Initialize(MainForm.RootPane)
Dim r As B4XRect = cvs.MeasureText(textToDraw,fx.DefaultFont(32))
Dim topPadding As Int = img.Height - r.Height
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
 
Upvote 0

PaulMeuris

Well-Known Member
Licensed User

This is my test case.
The text is centered around the red dot and is on the baseline.
I adjusted the rectangle width and height to make sure the text is completely inside.
B4X:
Sub Class_Globals
    Private Root As B4XView
    Private xui As XUI
    Private fx As JFX
    Private ziv1 As ZoomImageView
    Private pntext As Pane
End Sub
Public Sub Initialize
    B4XPages.GetManager.LogEvents = True
End Sub
Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    Root.LoadLayout("MainPage")
    Dim texttodraw As String = "English"
    Dim fnt As Font = fx.CreateFont("", 32, False, False)
    Dim cvs As B4XCanvas
    cvs.Initialize(pntext)
    DrawTextWithBorder(cvs,texttodraw,fnt,xui.Color_Blue,70,30)
    Dim img As Image = pntext.Snapshot
    ziv1.ImageView.SetBitmap(img)
End Sub
Sub DrawTextWithBorder (cvs1 As B4XCanvas, Text As String, Fnt As B4XFont, Clr As Int, CenterX As Int, CenterY As Int)
    Dim r As B4XRect = cvs1.MeasureText(Text, Fnt)
    Dim BaseLine As Double = CenterY - r.Height / 2 - r.Top
    cvs1.DrawText(Text, CenterX, BaseLine, Fnt, Clr, "CENTER")
    cvs1.DrawCircle(CenterX, CenterY, 3dip, xui.Color_Red, True, 0)
    r.Initialize(CenterX - r.Width / 2, CenterY - r.Height / 2, CenterX + r.Width / 2, CenterY + r.Height / 2)
    cvs1.DrawLine(r.Left, BaseLine, r.Right, BaseLine, xui.Color_Gray, 1dip)
    r.Width = r.Width + 2dip        ' text completely inside
    r.Height = r.Height + 2dip
    cvs1.DrawRect(r, xui.Color_Gray, False, 2dip)
End Sub
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…