一、基礎代碼示例
public GameObject node;
var rect = node.GetComponent<RectTransform>();Debug.Log($"anchoredPosition----{rect.anchoredPosition}");
Debug.Log($"offsetMin.x--{rect.offsetMin}");
Debug.Log($"offsetMax.x--{rect.offsetMax}");
Debug.Log($"rect.sizeDelta----{rect.sizeDelta}");
Debug.Log($"rect.rect----{rect.rect}");
Debug.Log($"rect.anchorMax----{rect.anchorMax}");
Debug.Log($"rect.anchorMin----{rect.anchorMin}");
場景結構
-
Parent 對齊方式
-
節點結構
二、X軸有拉伸的情況
1. 向上對齊
參數面板
- Left: Parent左邊(AD)到Child左邊(EH)的距離偏移,向右為正,向左為負。
- Right: Parent右邊(BC)到Child右邊(FG)的距離偏移,向左為正,向右為負。
- PosY: CD邊到Child中心點(M)的距離偏移,向上為正,向下為負。
- Height: Child的高度(EH或FG)。
日志輸出
anchoredPosition
anchoredPosition----(0.00, -20.00)
表示原點O(AB的中點)到Child中心點M的偏移。
offsetMin
和 offsetMax
offsetMin--(68.00, -70.00)
offsetMax--(-68.00, 30.00)
offsetMin
: 左下角錨點(A)到Child左下角(B)的偏移。offsetMax
: 右上角錨點(D)到Child右上角(C)的偏移。
sizeDelta
rect.sizeDelta----(-136.00, 100.00)
sizeDelta.x
: Child寬度相對Parent的寬度,即sizeDelta.x = -(68 * 2) = -136
sizeDelta.y
: 因Y軸未被拉伸,等于Child高度= 100
rect
rect.rect----(x:-32.00, y:-50.00, width:64.00, height:100.00)
表示Child自身中心(A)到自身左下角(B)的偏移。
anchorMax
和 anchorMin
rect.anchorMax----(1.00, 1.00)
rect.anchorMin----(0.00, 1.00)
anchorMin
: Child左下角錨點坐標。anchorMax
: 右上角錨點坐標。
當錨點發生變化時:
2. 居中對齊
參數面板
日志輸出
3. 向下對齊
參數面板
日志輸出
三、Y軸有拉伸的情況
1. 向左對齊
參數面板
- PosX: Parent左邊(AD)到Child中心點(M)的水平距離偏移,向右為正,向左為負。
- Top: Parent上邊(DC)到Child上邊(HG)的垂直偏移,向下為正,向上為負。
- Width: Child寬度(HG)。
- Bottom: Parent下邊(AB)到Child下邊(EF)的垂直偏移,向上為正,向下為負。
日志輸出
anchoredPosition
anchoredPosition----(100.00, 30.00)
O為原點(AB的中點),M為Child的中點。
offsetMin
和 offsetMax
offsetMin--(68.00, 30.00)
offsetMax--(132.00, 30.00)
offsetMin
: 左下角錨點(A)到Child左下角(C)的偏移。offsetMax
: 右上角錨點(B)到Child右上角(B)的偏移。
sizeDelta
rect.sizeDelta----(64.00, 0.00)
sizeDelta.x
: Child寬度= 64
sizeDelta.y
: 因X軸未被拉伸,sizeDelta.y = 0
2. 居中對齊
參數面板
日志輸出
3. 向右對齊
參數面板
四、XY軸同時拉伸
參數面板
- Left: Parent左邊(AD)到Child左邊(EH)的距離偏移,向右為正,向左為負。
- Right: Parent右邊(BC)到Child右邊(FG)的距離偏移,向左為正,向右為負。
- Top: Parent上邊(DC)到Child上邊(HG)的垂直偏移,向下為正,向上為負。
- Bottom: Parent下邊(AB)到Child下邊(EF)的垂直偏移,向上為正,向下為負。
日志輸出
五、無拉伸的情況(以左下角對齊為例)
參數面板
日志輸出
- sizeDelta.x: 等于Child寬度
- sizeDelta.y: 等于Child高度
總結
- anchoredPosition: 表示Child中心點相對于錨點原點的偏移。
- offsetMin / offsetMax: 表示Child與錨點之間的偏移量。
- sizeDelta: 表示Child相對于Parent的尺寸變化。
- rect: 表示Child自身的矩形區域。
- anchorMin / anchorMax: 定義Child的錨點位置。