Unity3D的UGUI布局錨點自動綁定關系


  

[MenuItem("CONTEXT/RectTransform/Auto")]
    public static void AutoRectAnior()
    {
        Debug.Log("自適應錨點");
        //獲得當前設置UI
        RectTransform rect = Selection.activeGameObject.GetComponent<RectTransform>();
        //獲取其父級
        RectTransform parent = rect.parent.GetComponent<RectTransform>();
        RectTransform canvas = rect.GetComponentInParent<Canvas>().GetComponent<RectTransform>();
        if (!rect || ! parent || !canvas)
        {
            Debug.Log("自適應錨點失敗,缺少對象!");
            return;
        }
        Bounds rectBounds = RectTransformUtility.CalculateRelativeRectTransformBounds(canvas, rect);//計算src的包圍盒
        Bounds parentBounds = RectTransformUtility.CalculateRelativeRectTransformBounds(canvas, parent);//計算tar的包圍盒

        float cMinX = 0.5f, cMinY = 0.5f, cMaxX = 0.5f, cMaxY = 0.5f;
        //獲取設置UI的寬和高
        float cWidth = rectBounds.size.x; //rect.sizeDelta.x * rect.localScale.x;
        float cHight = rectBounds.size.y;//rect.sizeDelta.y * rect.localScale.y;
        //獲取設置UI父級的寬和高
        float pWidth = parentBounds.size.x;//parent.sizeDelta.x * parent.localScale.x;
        float pHight = parentBounds.size.y;//parent.sizeDelta.y * parent.localScale.y;
        //重新計算錨點位置
        cMinX = (pWidth / 2 - (cWidth * rect.pivot.x - rect.anchoredPosition.x)) / pWidth;
        cMinY = (pHight / 2 - (cHight * rect.pivot.y - rect.anchoredPosition.y)) / pHight;
        cMaxX = (pWidth / 2 + (cWidth * (1 - rect.pivot.x) + rect.anchoredPosition.x)) / pWidth;
        cMaxY = (pHight / 2 + (cHight * (1 - rect.pivot.y) + rect.anchoredPosition.y)) / pHight;
        //重新設置UI的錨點位置
        rect.anchorMin = new Vector2(cMinX, cMinY);
        rect.anchorMax = new Vector2(cMaxX, cMaxY);
        //設置UI的相對距離
        rect.offsetMax = new Vector2(0, 0);
        rect.offsetMin = new Vector2(0, 0);

        Debug.Log("自適應錨點成功!");
    }

  上述綁定代碼未完善。。。后續完善


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM