How long is a string?

"How long is a piece of string?" may be a rhetorical question, but I'm hoping there's an answer to "How many pixels long will my string be when rendered into a GUI.Box?"

I want to grow my box to make it big enough to fit my string. GUI.skin.box.lineHeight * numberOfLines tells me how tall it will be, but there's no equivalent for character width. (And since not all characters are the same width this wouldn't work anyway.)

What I want is something like the MeasureText methods in Windows Forms.

As a workaround for now I'll split the string into lines, find the longest line, and multiply by an average character width.

You use GUIStyle.CalcSize:

private var content : GUIContent;

function Start() {
    content = new GUIContent("This is a Test");
}

function OnGUI() {
    var boxContentSize : Vector2 = GUI.skin.box.CalcSize(content);
    GUI.Box(Rect(0,0,boxContentSize.x,boxContentSize.y),content.text);
    var tfContentSize : Vector2 = GUI.skin.textField.CalcSize(content);
    content.text = GUI.TextField(Rect(0,boxContentSize.y,
                                      tfContentSize.x,tfContentSize.y),
                                 content.text);
}

This function does not take wordwrapping into account. To do that, you need to determine the allocated width and then call CalcHeight to figure out the wordwrapped height.

You can use GUIStyle.CalcHeight, or GUIStyle.CalcSize for it.

string str = “”;
string line = “”;
string words = caption2.Split(’ ');
for ( int w=0; w<words.Length; w++ )
{
Vector2 size = GUI.skin.label.CalcSize(new GUIContent(line));
Debug.Log ( size.x + “:” + size.y );
if ( size.x >= (540 - xpadding*2 - 10) )
{
line = words[w];
str += "

" + words[w];
}
else
{
if ( line != “” ) line += " ";
if ( line != “” ) str += " ";
str += words[w];
line += words[w];
}
}

			GUI.Label( new Rect(xoff + xpadding,ypadding,542-xpadding*2,540-ypadding), str );