- Home /
uGUI - resize RectTransform at runtime to fill entire screen
How do you resize a rect transform at runtime to fill the entire screen
I tried .sizeDelta = new Vector2 (Screen.width, Screen.height);
- however, this does not seem to go to the actual full size of the screen?
Answer by fafase · Jun 05, 2015 at 07:48 PM
Consider using the anchor position instead.
RectTransform rt = GetComponent<RectTransform>();
rt.anchorMin = Vector2.zero;
rt.anchorMax = Vector2.one;
rt.sizeDelta = Vector2.zero;
Note that it actually works if the parent occupies the whole screen.
good trick - any advice on how to understand how the anchors work?
Quite tricky to explain...
You have 4 anchors and 4 blue points for each UI item. Each blue point follows its corresponding anchor, so the bottom left is relative to bottom left anchor and so on.
The anchor is normalized to the screen size so you place with percentage of the full distance. This is use to move the anchor based on resizing the screen (if the canvas is meant to, default though).
So, if your anchor is at 0.5 then it is always in the middle, if at 0.2 then it will always be at 20% of the full dimension, so 200 if dimension is 1000 and 200 if the full is 600.
The blue point is following that anchor by the distance you gave it. So if your blue point is on the anchor, the blue point has the same behaviour and rescale based on screen size. If teh blue point was 200 to the right of the anchor then anytime you rescale, this 200 is kept which represents a small portion on large screen but a large portion on small screen.
On the other hand, if you want to keep the dimensions of a UI regardless the screen, you need the anchor not to move with rescaling. You do so by placing them joint together in the middle of the UI item. Then the distance between the four corners and the anchor points which is now a single point in the middle, will remain the same. So a picture of 200x200 will remain that dimension on any screen size.
Just a quick introduction though.
@fafase thanks for the answer and the explanation!
One typo: rt.sizeDelta = Vector2.zero;
you missed the 2
. :P
Also, do you have any idea what to do when the parent's RectTransform isn't set to stretch( does not occupy the whole screen) or even worse if we have nested RectTransforms.
How would we go about this? maybe by recursively drilling upwards and setting the anchors as you did in your answer till we get to the Canvas?
Worked for me by adding...
rt.anchoredPosition = Vector2.zero;
Yes this answer just sets the transform to the correct size but it can still be off center. I made it work by setting offset$$anonymous$$ax and offset$$anonymous$$in to zero ins$$anonymous$$d of setting sizeDelta. But setting the position would also work.