Search Unity

Question Encapsulate bounds not correct with UI scale mode

Discussion in 'UGUI & TextMesh Pro' started by lejean, Jun 16, 2020.

  1. lejean

    lejean

    Joined:
    Jul 4, 2013
    Posts:
    392
    I'm trying to encapsulate recttransforms children with a single box which works fine with a canvas with "Constant pixel size" but once I change it to "Scale with Screen Size" they are not encapsulated correctly.
    Does anyone have any idea what's wrong?

    Constant pixel size example
    bounds constant pixel size.png

    Scale with screen size
    bounding scale with screen.png

    The code

    Code (CSharp):
    1. public class GetBounds: MonoBehaviour
    2. {
    3.     public List<RectTransform> rects;
    4.  
    5.     private void Update() {
    6.         if (Input.GetKeyDown(KeyCode.D)) {
    7.             CalculateBounds(GetComponent<RectTransform>(), 1);
    8.         }
    9.     }
    10.  
    11.     void CalculateBounds(RectTransform transform, float uiScaleFactor) {
    12.         Bounds bounds = new Bounds(transform.position, new Vector3(transform.rect.width, transform.rect.height, 0.0f) * uiScaleFactor);
    13.  
    14.         foreach (RectTransform child in rects) {
    15.             Bounds childBounds = new Bounds(child.position, new Vector3(child.sizeDelta.x, child.sizeDelta.y, 0.0f) * uiScaleFactor);
    16.             bounds.Encapsulate(childBounds);
    17.         }
    18.  
    19.         transform.sizeDelta = bounds.size;
    20.         transform.position = bounds.center;
    21.     }
    22. }
     
  2. Hosnkobf

    Hosnkobf

    Joined:
    Aug 23, 2016
    Posts:
    1,096
    Best way is to set the size delta to zero and instead set the anchor min / max.