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

相关文章
相关标签/搜索