Scale down a rectransform to fit its parent rectransform (not using anchors).

Hi there,

I’m having trouble due to lacking math skills. i appreciate if someone helps me solve this case

I have a uGUI canvas with 2 rectransforms in it (parent and child)

  • parent recttransform width and height is (400x700) without using anchors.
  • child rectransform width and height will always be bigger (random) for example 600x900.

I want to scale child’s rectransform down so it fits within parent rectransform with maintianing its aspect ratio.

This problem is killing me, thanks in advance for help.

You should first consider whether you can just use an Aspect Ratio Fitter component on the child to take care of this for you. There is a “fit in parent” option. I have heard that Unity’s implementation of this is kinda inefficient, though, so if you need this behavior for a lot of objects you might want to do some performance testing.

If you want to write your own script, you’d need to scale the child down by a ratio of (parent size) / (child size). If you want to preserve aspect ratio while fitting within the parent, then scale both the width and the height by whichever ratio is smaller.

The size of UI objects is a bit tricky because they sort of have two “sizes”–they have sizeDelta, and also scale. So (A) you should think about which one of those things you want to modify in the child, and (B) if you want to fully cover your bases, you need to take both of those into account when calculating your scaling ratio in the first place.

1 Like

Thank you very much, you are a life saver.