How to get the height of the GUI.TextBlock?

pg:https://playground.babylonjs.com/#HJZBRG#218
Hey~ALL. The height attribute can only get ‘100%’ . Where is the trick ?
20211028141145
20211028141221

You can use element.heightInPixels if you want to get the exact height in pixels.

I did try this. But the result was 0

That is because you are adding it to a stack panel that still has no height and was not added to any control, so it cannot calculate its height. A single frame after (after a single render) you will get the right result. This is of course not a solution, just to show that the value does update:

GUI List BillBoard | Babylon.js Playground (babylonjs.com)

Maybe @msDestiny14 can help further with how to get it in the same frame

3 Likes

Yep let’s take a look at what’s going on.

If we look into the GUI code we find that the computed values are not calculated till after the first frame of render. The logic for this is in _processMeasures function in Babylon.js/textBlock.ts at master · BabylonJS/Babylon.js · GitHub

A trick to get the height before the first render would do what the measure function is doing. Something like this line…

let newHeight = (this.paddingTopInPixels + this.paddingBottomInPixels + this._fontOffset.height * this._lines.length) | 0;

https://playground.babylonjs.com/#XCPP9Y#9515 note I had to know the fontOffsetHeight (font size + additional padding). This should be something included with the font.

By default when you create a textBlock the size will be 100% w/h unless you set resizeToFit = true. What this will do is adjust the bounding box of the text to fit with the size of the text you typed.

Final bonus note: stack panel must use pixel values. You can’t have 100% of something that is changing sizes based on what’s inside it.

Happy to answer any follow up questions to this. Let me know!

2 Likes