- Home /
How to know the font height in pixels (and other attributes) of a text?
I end up making a function that calculates the height of a text inside of a multi-line element. Taking account the height of the font, the margin of the element and the space between lines, im pretty sure I could improve my guess (kind of random at the moment). But I have no idea how to access that info.
Also I have a random guess to fit the width, which works quite accurate at the moment. But since the font is not monospace, it could have some error.
Here the code:
private int FormatTextForUIElements(string inputText, out string resultText, int elementWidth)
{
if(!inputText.Contains("\n"))
{
string[] aWord = inputText.Split (' ');
string line = string.Empty;
resultText = string.Empty;
foreach(string word in aWord)
{
// Fits the word in the line?
if((line.Length + 1 + word.Length)*6.5 < elementWidth)
{
line += " " + word;
}
else
{
// Its result empty?
if(resultText.Equals(string.Empty))
{
resultText = line;
}
else
{
resultText += "\n" + line;
}
line = word;
}
}
// Its result empty?
if (resultText.Equals(string.Empty))
{
resultText = line;
}
else
{
resultText += "\n" + line;
}
}
else
{
resultText = inputText;
}
int result = resultText.Split ('\n').Length;
return result * 17 + 6;
}
In case you want to try it:
public int elementW = 130; // public so you can play with it on the editor
[...]
string formatedText = string.empty;
string text = "Some long text that will be formated to fit the UI element";
int heightForTextBox = FormatTextForUIElements (text, out formatedText,elementW);
string test = GUI.TextArea (new Rect (0, 0, elementW, heightForTextBox), formatedText);
Answer by Owen-Reynolds · Jul 09, 2014 at 03:32 PM
GUIStyle.CalcSize.
It requires you to make a "fake" GUIStyle, using the font and size you have. But then you can just measure a word.
There are some small issues. I use one font where, for words like "To", a TextMesh tucks the "o" under the right bar of the "T", but calcSize doens't know that, so returns a too-large width.
For non-monospace fonts, it will requiere a personalized function to get the real width.
But right know I am more concerned to get a more accurate height (since I already made my own function). I expect to be somewhere a function like "fontsize" or something (and not the "scalable" thing some components have) to call, and also to access the style.somecontrol.margin But didnt found yet in documentation something like that.
This approach doesn't work to Unity 4.6+ Text component. There is anyway to measure the pixel size of a Text in Unity 4.6+?