height and width of label/box depending on amount of text

Hey there!

Perhaps I’m not using the right search terms, but I can’t seem to find the answer to this question.

I would like to have the height and width of a label/box be flexible with the amount of text. So for example, if the string contains nothing I want the width and height to be 0. But when the string contains 30 characters I want the box the be large enough to fit the text and background of the label nicely and when the width reaches a specified amount I want the text to go to a next row.

I am wondering if there is an easy way to do this, I can’t seem to find it. Thanks a lot for your help.

York.

Just use GUILayoutUtility.GetRect(). It returns a Rect that’s big enough to hold your content - be it text, images or both. The nice thing is, that it doesn’t actually draw anything so you can modify that rect if you wish before drawing.

Use it like this:

Rect labelRect = GUILayoutUtility.GetRect(new GUIContent("This is some text"), "label");

Now you have a nice rect which you can use directly to actually draw the label OR first do other stuff (like going to the next row and such).

Drawing the label is as easy as

GUI.Label(labelRect, "This is some text");

That should give you a starting point.

This is an old thread, but while I was trying to do the same thing, I found that a better answer is to use GUIStyle.CalcMinMaxWidth. GetRect reserves layout space, but CalcMinMaxWidth does not.