一、在代碼中動態改變RectTransform大小的方法如下所示:
1:直接對sizeDelta屬性進行賦值,其中X和Y可以對應理解成width和height。sizeDelta的具體含義:若anchors是一個點的話則代表寬高,否則為到錨點的距離
var rt = gameObject.GetComponent<RectTransform>();
rt.sizeDelta = new Vector2(100, 30);
2:使用SetSizeWithCurrentAnchors函數來進行設定,其中Horizontal和Vertical分別對應寬和高。此函數受當前錨點和中心點的影響。
var rt = gameObject.GetComponent<RectTransform>();
rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 100);
rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 30);
3:使用SetInsetAndSizeFromParentEdge函數來進行設定。此函數不受錨點和中心的影響,其中第一個參數代表對齊方式,第二個參數為距離邊界的距離,第三個參數為寬度。
var rt = gameObject.GetComponent<RectTransform>();
rt.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, 0, 100);
rt.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Bottom, 0, 30);
二、獲取RectTransform大小的方法
1:直接獲取sizeDelta屬性值,其中X和Y可以對應理解成width和height。sizeDelta的具體含義:若anchors是一個點的話則代表寬高,否則為到錨點的距離
2:rect.size的屬性值,這里不受anchors的影響
var rt = gameObject.GetComponent<RectTransform>();
Debug.Log("===>" + rt .rect.size);