- Home /
Measure text size for UI Text
I'm trying to implement a dialog box that displays some text that wraps to a given width and resizes vertically. It also need to have a maximum height, such that if text would overflow beyond that, I can detect this and display the extra text later.
This would be pretty simple if the 4.6 UI had a way to measure text size, similar to GUIStyle.CalcSize()
, but it doesn't seem to. So, alternatives I've tried:
Using a ContentSizeFilter
to make the Text component adjust its vertical size. The problem is it doesn't have a way to specify a max height, so it will just show all of the text.
Setting the height of the Text component to some max height, and then measuring its preferred height using LayoutUtility
. This is nice in that I can make sure the Text does not exceed some height, and I can tell when it has too much content (when preferred height is greater than actual height), but I don't know how to figure out what text is showing properly, and what text is truncated and will need to be displayed in a second dialog box.
As a fallback, I could add text one word at a time until I see that the text is truncated, but that seems very inelegant, and I believe you need to wait a frame after each layout change to measure the new size.
Has anyone found a better solution? I would really appreciate the help!
Answer by salmelo · Oct 04, 2015 at 01:17 AM
You could try looking into TextGenerator. The Text component actually uses that internally, so in theory it should work.