- Home /
How to calculate the height of wordwrapped gui text
I am currently using a single font and altering it's size to put text into a GUI.Label. I use the following code to make sure that the text fits my label:
var customButton : GUIStyle; static var content = new GUIContent(); var string = "Contents of label"; var sizeX = 200; var sizeY = 40; var startPosX = 20; var startPosY = 20;
customButton.wordWrap = false; content = GUIContent(string); customButton.fontSize = 60; var boxContentSize : Vector2 = customButton.CalcSize(content); while (boxContentSize.y > sizeY || boxContentSize.x > sizeX) { customButton.fontSize -= 5; boxContentSize = customButton.CalcSize(content); }
GUI.Label (Rect (startPosX,startPosY,sizeX,sizeY), string, customButton);
This code reduces the font size until the text fits the box size. If I print out the values of boxContentSize.x and boxContentSize.y they seem reasonable values based on the assumption that they are in screen pixels.
As I sometimes want to put in longer strings and wrap the text I set wordWrap = true. However, when I do this, the boxContentSize.y is a very large value and does not seem to relate to the pixel size in the Y direction. I've tried using
customButton.CalcHeight(content, boxContentSize.x);
but this also gives a value in boxContentSize.y that is larger than expected. Can anyone explain what width value is supposed to be passed in CalcHeight and how I get a reasonable value for the height of the text based on a given font size? Any help would be appreciated.
CalcHeight need to know the width of the area you want to insert the wordwrapped text to be able to calculate the height. In your case you need sizeX. customButton.CalcHeight(content, sizeX);
Thanks. It seems I was just using the wrong width as the height is now a sensible value. I just changed the while loop to compare the height with sizeY and everything is fine.
Answer by yoyo · Feb 07, 2011 at 05:51 PM
You need both GUIStyle.CalcSize and GUIStyle.CalcHeight.
Your answer
![](https://koobas.hobune.stream/wayback/20220613103235im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
GUIStyle.CalcSize giving wrong answer 0 Answers
Is there a way to measure the pixel with/height of a string with a given font? 2 Answers
Possible to change GUI.Label fontsize without using GUIStyle? 1 Answer
GUIBox fontSize without changing other labels? 3 Answers
Sometimes the GUI selectively doesn't render some letters 1 Answer