UGUI—sizeDelta以及獲取UI寬高的方式

sizeDelta是什麼

通俗理解: sizeDelta = 元素自己寬高 - 錨點矩形寬高 當錨點四個手柄在一塊兒時,錨點矩形寬高爲0,這時獲得的sizeDelta就是元素自己寬高。c#

獲取UI寬高的方式

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class printpositon : MonoBehaviour
{
    
    private Transform image2;

    private void Start()
    {
        image2 = GameObject.Find("Image2").transform;
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Debug.Log("----------UpdateCanvas----------------");
            RectTransform rect = image2.gameObject.GetComponent<RectTransform>();
            Debug.Log("sizeDelta:" + rect.sizeDelta);  --方法一
            Debug.Log("rect.width:" + rect.rect.width); --方法二
            Debug.Log("rect.height:" + rect.rect.height);
            Debug.Log("rect.size:" + rect.rect.size);  --方法三
        }
        
    }
}
複製代碼

方法一:sizeDelta:只有當錨點的四個手柄合併在一塊兒時,此時獲得的sizeDelta纔是物體的寬高。

方法二:rect.width/rect.height

方法三:rect.size

相關文章
相關標籤/搜索