TextBlock resize to fit fixed width

I’m trying to make little piece of code for auto-resize fontSize, until text with not fit textblock width, like this:

while (this.text_coins_value.lines[0].width > 70) {
this.coins_value.fontSize -= 2 // yes, some addition work with “px” here
}

How can i force update calculation of this.coins_value.lines[0].width inside this loop?
_markAsDirty() Is not working, update still happen in next render loop.
Sooo…any way to force redraw or force recalculate string with?

Hey and welcome!

I could perhaps expose a textBlock.measureText(text) API?

1 Like

measureText exposed in canvas2D API. Not in TextBlock.
And doing this way is a more deep hack.
I want stay on babylon level.
Soo… how i can force update all calculation in TextBlock? Or maybe some basic Container api for this?

No I meant expose the way Textblock evaluate each line width. So after adding the API for you you could do:

do {
this.coins_value.fontSize -= 2 // yes, some addition work with “px” here

}
while (this.coins_value.measureText(this.text_coins_value.lines[0]) > 70) {

as the TextBlock.measureText API is not available, is there a recommended way to resize text to fit in its container?

@msDestiny14 can help with this :slight_smile:

There are a couple of solutions to this:

Option one is to calculate it manually using the text pixel size and then the number of characters in the text. Or you can get the container size and the text length and determined what the right font size should be.

Another option is to use word wrap feature: textblock.textWrapping https://playground.babylonjs.com/#XCPP9Y#8956
If you see in this playground the text is wrapping to a container’s width value.

What I would not do is use resizeToFit which will resize the container to fix the text. It’s a little misleading in my opinion.

2 Likes