- Home /
Reliable way to get width/height of UI element?
I'm creating UI elements that need to know their width and height in order to arrange their children correctly. I've been using the following to calculate the width and height of the element:
var rectTransform = GetComponent<RectTransform>();
float width = rectTransform.rect.width;
float height = rectTransform.rect.height;
It works in many cases but there are some cases when the current element and its parent is stretched that rectTransform.rect.width returns a negative value. The rectTransform.rect.sizeDelta.x/y is also zero in these cases.
I wonder if there is a reliable way to calculate the current size of a UI element regardless how it is anchored?
Answer by ondere · Apr 12, 2018 at 11:01 PM
its sizeDelta
var rectTransform = GetComponent<RectTransform>();
float width = rectTransform.sizeDelta.x;
float height = rectTransform.sizeDelta.y;
This is not true. With stretched anchors and bottom/top/left/right offsets set to 0 sizeDelta of RectTransform is (0,0) even though the actual size of rect should be size of its parent. Using size.Delta is most unreliable answer possible.
Answer by DoTA_KAMIKADzE · May 22, 2015 at 08:55 PM
Negative rect value means that your UI is not visible, because...well because its width/height is negative, pretty obvious? But if you want to get only absolute value for some calculations then use absolute value (Abs).
Also the difference between sizeDelta and rect is well described THERE.
The UI element is visible and renders as expected on the screen.
Without the code and screens of your UI setup/hierarchy I can't tell you why your UI element reports negative width even though that it has positive. If you want me to find that out then I'll need all of those.
I'm also interested in this problem. I am stretching a panel vertically and I'm trying to return its height somehow. The thing is that stretched elements in rect transform have no height.They are measured with distance to the anchor, so you can't assign or natively return the height because there is none.
Is it possible to measure the height in a more non-conventional way?
Thank you
Answer by skrad · Nov 13, 2015 at 09:53 PM
I have just found an ugly solution like this.
In the inspector navigate to your stretched Rect Transform and hard code the left, top, right, bottom values somewhere in your code.
Then simple do this:
float realWidth = (float) (Screen.width - hard_Code_Left - hard_Code_Right);
float realHeight = (float) (Screen.height - hard_Code_Top - hard_Code_Bottom)
what means your hard_Code_Left, hard_Code_Right, hard_Code_Top, hard_Code_Bottom?
Hello!
Those are the Number values you need to check in your actual RectTransform using the inspector, and put those in variables.
for example: float hard_Code_Left = 115f;