- Home /
Font Metrics
I'm building a HUD dynamically using TextMesh to draw text.
It would be incredibly useful to be able to determine what the dimensions of a given string would be, in pixels, using a given font without scaling, so that I can write code to perform sensible layout and aspect ratio decisions, yet I can't seem to find a way to obtain this information at the point when I update the mesh transform (I've seen the GUI CalcSize/CalcScreenSize functions, but those can only be used in an OnGUI handler!).
How do I obtain the metrics for a given font/string?
Answer by toothycat · Jul 29, 2011 at 03:00 PM
Looks like GUIStyle.CalcSize()
is available even outside OnGUI()
, so the following implements an XNA
-like MeasureString()
:
public static class Extensions
{
static GUIStyle s_guiStyle = new GUIStyle();
public static Vector2 MeasureString( this Font _font, string _string )
{
s_guiStyle.font = _font;
return s_guiStyle.CalcSize(new GUIContent(_string));
}
}
Still holding out for something not so nastily hacky though!
Nice hack man! :)
Still hoping to find something equivalent in the new UI