localPosition:表示的是子物体的pivot相对于父物体RectTransform的中心点pivot的相对坐标。
anchoredPosition3D:表示的是子物体的pivot相对于锚点anchor的相对坐标。
anchorMax:右上方锚点位置(所在位置与父物体RectTransform宽度和长度的比例)
anchorMin:左下方锚点位置(所在位置与父物体RectTransform宽度和长度的比例)
offsetMax:从右上方锚点位置到UI右上方坐标的偏移向量
offsetMin:从左下方锚点位置到UI左下方坐标的偏移向量
sizeDelta:offsetMax - offsetMin
rect:RectTransform中的属性,不与UI元素所在的位置有关
SetSizeWithCurrentAnchors(Animations.Axis axis, float size):可以通过直接设置rect中的width和height值来改变UI元素的大小。
SetInsetAndSizeFromParentEdge(RectTransform.Edge edge, float inset, float size):根据父物体的Edge(某一边)去布局
写了个编辑器拓展,选中gameObject,按快捷键会输出一些RectTransform的信息。
using UnityEngine;
using UnityEditor;
public class TestEditor
{
[MenuItem("MyTool/ShowRectTransform", true)]
private static bool Validate()
{
if (Selection.objects.Length > 0)
return true;
else
return false;
}
[MenuItem("MyTool/ShowRectTransform %_q", false)]
private static void MyToolShowRectTransform()
{
GameObject go;
//Selection.objects 返回场景或者Project中选择的多个对象
foreach (Object item in Selection.objects)
{
go = ((GameObject)item);
RectTransform rect = go.GetComponent<RectTransform>();
Debug.Log(go.name + ".localPosition=====" + rect.localPosition);
Debug.Log(go.name + ".anchoredPosition3D=====" + rect.anchoredPosition3D);
Debug.Log(go.name + ".anchorMax=====" + rect.anchorMax);
Debug.Log(go.name + ".anchorMin=====" + rect.anchorMin);
Debug.Log(go.name + ".offsetMax=====" + rect.offsetMax);
Debug.Log(go.name + ".offsetMin=====" + rect.offsetMin);
Debug.Log(go.name + ".sizeDelta=====" + rect.sizeDelta);
Debug.Log(go.name + ".rect=====" + rect.rect);
//rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 100);
//rect.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, 0, 622);
}
}
}
1. localPosition与anchoredPosition3D(anchoredPosition)
localPosition表示的是子物体的pivot相对于父物体RectTransform的中心点pivot的相对坐标。
anchoredPosition3D表示的是子物体的pivot相对于锚点anchor的相对坐标。
也就是说,当锚点与父物体RectTransform的中心点重合时,localPosition与anchoredPosition相当。



可以看到两者相等,如果移动锚点位置,则只改变anchoredPosition。
如果将锚点打开,则anchoredPosition为中心点到锚点正中央的位置相对坐标。
2. offsetMax与offsetMin
offsetMax:从右上方锚点位置到UI右上方坐标的偏移向量
offsetMin:从左下方锚点位置到UI左下方坐标的偏移向量
当锚点没有打开时:


当锚点打开时:


offsetMax与offsetMin可以修改,当锚点打开到最大时,可以用来动态调整子物体到边界的距离。
3.sizeDelta
sizeDelta=offsetMax - offsetMin
在锚点没打开的时候,就是子物体的长和宽,可以用来动态修改长宽。

打开的时候,就是锚点的框框长宽跟子物体Rect长宽的差值。
4. rect(只读)
rect中的属性,不与UI元素所在的位置有关,只和其自身属性相关,所以其中的rect.width和rect.height属性就可以让我们在任何情况下取得子物体的大小,而rect.x和rect.y表示的是以Pivot为原点,UI元素左下角的坐标:




5.SetSizeWithCurrentAnchors(Animations.Axis axis, float size)
可以通过直接设置rect中的width和height值来改变UI元素的大小。
需要强调的是,在动态设置width或者length时,由于PosX,PosY不变,所以全看中心点设在哪里,设在最左边,那么只会往右拉宽,设在最上面,只会往下拉宽。


6.SetInsetAndSizeFromParentEdge(RectTransform.Edge edge, float inset, float size)
根据父物体的Edge(某一边)去布局

rect.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, 0, 622);
说的是,让子物体距离右边长度为零,设置其宽度为622。
网友评论