Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to scale & move a RectTransforms so that it match exactly another RectTransforms?

Discussion in 'UGUI & TextMesh Pro' started by Le_Tai, Apr 20, 2016.

  1. Le_Tai

    Le_Tai

    Joined:
    Jun 20, 2014
    Posts:
    442
    I want to be able to warp a RectTransforms so that it match another RectTransforms regardless of hierarchy position. Here my code

    Code (CSharp):
    1. public void ScaleToRectTransform (RectTransform
    2. {
    3.     rt.anchoredPosition = rt.InverseTransformPoint (target.TransformPoint (target.anchoredPosition));
    4.     rt.sizeDelta = rt.InverseTransformVector (target.TransformVector (target.sizeDelta));
    5. }
    It doesn't scale it the way I want.
     
    Last edited: Apr 20, 2016
  2. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
  3. Le_Tai

    Le_Tai

    Joined:
    Jun 20, 2014
    Posts:
    442
    I know about those method, they only give me 4 corners, but AFAIK there no way to set 4 corners of a RectTransform. There are offsetMax/min but they are relative to anchor
     
  4. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    There's size delta:
    Code (csharp):
    1.  
    2. float width = Vector3.Distance(corners[0], corners[3]);
    3. float height = Vector3.Distance(corners[0], corners[1]);
    4. itemRt.sizeDelta = new Vector2(width, height);
    5.  
     
    Last edited: Apr 20, 2016
    unity_sdTL7CPH4nQhAw likes this.
  5. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    @OPtimus_Maximus - Did that help?

    You should be able get exactly the same size for child of some RectTransform and canvas parented RectTransform, no matter what the scaling of child's parent is.
     
  6. Le_Tai

    Le_Tai

    Joined:
    Jun 20, 2014
    Posts:
    442
    Thanks for your help, but your size snippet only work if the anchors are grouped togethers, remember that size delta is relative to anchor position.
     
  7. Le_Tai

    Le_Tai

    Joined:
    Jun 20, 2014
    Posts:
    442
    apparently the solution is

    Code (CSharp):
    1. RectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis axis, float size);
     
  8. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    @OPtimus_Maximus

    Well, it's just a matter of setting value, you already have the correct size.

    Code (csharp):
    1.  
    2. itemRt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, width);
    3. itemRt.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height);
    4.  
    EDIT - ouch, missed your post!
     
  9. AdityaMGametion

    AdityaMGametion

    Joined:
    Jul 24, 2018
    Posts:
    1
    Perfect!!