- Home /
Is there a way to measure the pixel with/height of a string with a given font?
I see the GUI Layout stuff for automatically laying out UIs in certain ways. And that is pretty cool overall. However, it is also really helpful to be able to precisely center various arbitrary strings (arbitrary thanks to localization or other factors, which has been an interesting challenge for me in past projects). With both DirectX and GDI, there is essentially a MeasureString method that you can pass a font, some text, and a max width to, and it gives back a Size property saying how wide/tall that text will be given the parameters you passed in. Surely there's something similar in Unity?
Answer by runevision · Mar 19, 2010 at 10:10 AM
You can use GUIStyle.CalcSize() which takes a GUIContent as parameter:
Vector2 sizeOfLabel = myStyle.CalcSize(new GUIContent("My string"));
You can use this on a GUIStyle you have made that uses the font of your choice.
GUILayoutUtility.GetRect() reserves space for the rect it returns, so it may influence your GUI layout. If you want a function that does not have side effects, CalcSize is the way to go.
Answer by Eric5h5 · Mar 19, 2010 at 03:54 AM
Yes, you can use GUIUtility.GetRect(), where you pass in GUIContent and GUIStyle and get back a Rect. (Plus various overloads.)
Your answer
Follow this Question
Related Questions
Change Font Style OnMouseEnter 0 Answers
GUI text font change 3 Answers
Help with GUILayout and tooltip(C#) 1 Answer
Cant change color of 3dText/Text Mesh 3 Answers
Is there a method for getting Scrollview to work in a GUILayout Window? 2 Answers