- Home /
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.
Thanks all -- obviously I didn't RTF$$anonymous$$ closely enough! I was busy looking at GUIStyle variables and neglected to review the functions, my bad.
Answer by skovacs1 · Dec 03, 2010 at 09:44 PM
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.
Answer by Maarten · Dec 03, 2010 at 09:35 PM
You can use GUIStyle.CalcHeight, or GUIStyle.CalcSize for it.
Answer by franky303 · Sep 20, 2012 at 11:23 AM
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 += "\n\n" + 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 );
Your answer
Follow this Question
Related Questions
GUI text font change 3 Answers
Limit on GUI Components? 0 Answers
Using "fonts" that are actually images for a multi-outline effect. 2 Answers
Dialouge text. 1 Answer
Unity GUI text displaying as noise 1 Answer