Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

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

Discussion in 'Unity UI (uGUI) & TextMesh Pro' started by jGate99, Oct 11, 2019 at 7:50 PM.

  1. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    866
    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.
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    1,216
    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.
     
    jGate99 likes this.
  3. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    866
    Thank you very much, you are a life saver.