x


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?

more ▼

asked Mar 19 '10 at 01:48 AM

x4000 gravatar image

x4000
504 23 25 40

(comments are locked)
10|3000 characters needed characters left

2 answers: sort oldest

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.

more ▼

answered Mar 19 '10 at 10:10 AM

runevision gravatar image

runevision ♦♦
8.1k 29 46 112

Thanks very much!

Mar 19 '10 at 03:10 PM x4000

yes, very helpfull answer thanks

Oct 21 '10 at 10:52 AM Jean Fabre
(comments are locked)
10|3000 characters needed characters left

Yes, you can use GUIUtility.GetRect(), where you pass in GUIContent and GUIStyle and get back a Rect. (Plus various overloads.)

more ▼

answered Mar 19 '10 at 03:54 AM

Eric5h5 gravatar image

Eric5h5
80.3k 42 132 521

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3697
x241
x137

asked: Mar 19 '10 at 01:48 AM

Seen: 3986 times

Last Updated: Mar 19 '10 at 01:48 AM