B4J Question How to render text to images?

xulihang

Active Member
Licensed User
Longtime User
Hi there,

I want to get the image of a single character like "我" and "?".

I tried using B4XCanvas's MeasureText and Canvas's drawText:

B4X:
Dim emptyPane As Pane
emptyPane.Initialize("")
Dim cvs1 As B4XCanvas
cvs1.Initialize(emptyPane)
Dim r As B4XRect=cvs1.MeasureText(s,f)
Dim width,height As Double
width=r.Width
height=r.Height
Dim X,Y As Double
X=0
Y=height
Dim Canvas1 As Canvas
Canvas1.Initialize("")
Canvas1.SetSize(width,height)
Canvas1.DrawText(s,X,Y,fx.DefaultFont(30),fx.Colors.Black,"LEFT")
Return Canvas1.Snapshot2(fx.Colors.Transparent)

But I find its edges are cut a bit.

Font size: 16


Font siz: 30
 

MicroDrie

Well-Known Member
Licensed User
Longtime User
B4X:
width=r.Width
height=r.Height
The dimensions of the image are not square, but rectangular with a size of 69 x 72 pixels. By making the height and width the same, you lose the bottom of the image. It seems that the height and width are the same height for the underlying canvas so the bottom of the image is not shown.

update: add missing canvas reference in text
 
Last edited:
Upvote 0

xulihang

Active Member
Licensed User
Longtime User
I switched to using JavaFX's Text node to render text

B4X:
    Dim text As JavaObject
    text.InitializeNewInstance("javafx.scene.text.Text", Array(s))
    text.RunMethod("setFont", Array(f))
    Dim n As Node = text
    Return n.Snapshot2(fx.Colors.Transparent)
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…