我的環境
Unity 5.3.7p4
在運行時動態的設置UI元素的錨點和中心點。
設置坐標
對於UI上的元素,使用anchorPosition,而不是localpostion,因為Recttransform可以設置錨點。
設置Anchor
修改offsetMax不生效
使用下面這段代碼設置Anchor並不會生效,盡管他和你在屬性面板看到的值是一樣的。
retRoot.offsetMin = Vector2(0,0)
retRoot.offsetMax = Vector2(0,0)
SetInsetAndSizeFromParentEdge
使用SetInsetAndSizeFromParentEdge函數來進行設定。此函數不受錨點和中心的影響,其中第一個參數代表對齊方式,第二個參數為距離邊界的距離,第三個參數為寬度或高度。
示例:
---設置為左上角
retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0, width)
retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, height)
修改Anchor不會影響Pivot
修改Anchor之后,並不會影響Pivot
設置Pivot(中心點)
pivot是一個0~1之間的值 示例:retRoot.pivot = Vector2(0, 0)
其中0,0為左下角
當你要做動畫,設置父容器的Pivot就可以控制動畫的出現方向
查看Pivot
在Editor的工具欄將Pivot的模式設置為這個模式(Pivot Local),才能查看到正確的Pivot。
示例代碼
設置左上、左下、右上、右下四個錨點,並同時設置中心點。
---@param retRoot UnityEngine.RectTransform
function TipsHelper.SetTipsAnchor(retRoot, anchor, width, height)
if not retRoot then
print("[error] SetAnchor失敗,RectTransform不能為空")
return
end
if anchor == Constants.Anchor.LeftTop then
retRoot.pivot = Vector2(0, 1)
retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0, width)
retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, height)
elseif anchor == Constants.Anchor.LeftBottom then
retRoot.pivot = Vector2(0, 0)
retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0, width)
retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Bottom, 0, height)
elseif anchor == Constants.Anchor.RightTop then
retRoot.pivot = Vector2(1, 1)
retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, 0, width)
retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, height)
elseif anchor == Constants.Anchor.RightBottom then
retRoot.pivot = Vector2(1, 0)
retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, 0, width)
retRoot:SetInsetAndSizeFromParentEdge(RectTransform.Edge.Bottom, 0, height)
end
end
參考資料
參考:http://www.arkaistudio.com/blog/334/unity/unity-ugui-原理篇三:recttransform