Unity學習筆記(4) --- Unity的界面排版: RectTransform
來自: http://blog.csdn.net//likendsl/article/details/50556580
看Unity3D文檔像看國內教課書一樣,一些概念,不懂的時候看還是不懂,明白了以后再看,好像也沒有說錯。好幾個做Unity3D的朋友跟我吐槽過U3D的文檔質量,相比Apple貼心的技術文檔相去甚遠。
話雖這么說,權威的資料當然還是官方的,建議先仔細讀一遍,不懂的再往下讀:
http://docs.unity3d.com/Manual/UISystem.html
網上的教程大多泛泛而談,就不吐槽了。好在還找到了一篇比較好的解讀,在此謝謝作者白貓。文章鏈接在下面
http://www.cnblogs.com/whitecat/p/4159815.html
uGUI里面AutoLayout比較特別,我就此詳細描述一下,希望能減少“教科書”的理解障礙。
RectTransform的理解
UI元素有專門的RectTransform組件來描述元素的幾何信息,繼承于Transform,Inspector中其屬性如下圖。
Anchors,錨點
我們首先需要認識Anchors。官網上的圖片很好表達了Andhors的功能,請恕我實踐下拿來主義。
善于觀察的同學可能已經發現,不管什么情況,button的四個頂點到相應錨點的相對位置是不變的:
當4個錨點都在一起的時候,RectTransform會顯示Pos X,Pos Y,Width,Height四個屬性可供修改。
當不在一起的時候,RectTransform可調整的屬性會有變化。
Anchors的Min和Max分別是正規化的值(從0到1),表示占父RectTransform的百分比,下圖中AnchorMin=(0.1,0.1) AnchorMax=(0.9,0.9)
Pivot,UI的中心點
UI元素的旋轉和縮放是圍繞pivot進行的。RectTransform組件中,Pivot屬性是一個正規化的二維向量,用來描述中心點在本身矩形大小的位置。默認值為(0.5, 0.5),即幾何中心。
以上是RectTransform可視化的編輯屬性,實際上RectTransform類的屬性是怎樣的?查閱RectTransform的官方文檔如下:
anchoredPosition
The position of the pivot of this RectTransform relative to the anchor reference point.
anchoredPosition3D
The 3D position of the pivot of this RectTransform relative to the anchor reference point.
anchorMax
The normalized position in the parent RectTransform that the upper right corner is anchored to.
anchorMin
The normalized position in the parent RectTransform that the lower left corner is anchored to.
offsetMax
The offset of the upper right corner of the rectangle relative to the upper right anchor.
offsetMin
The offset of the lower left corner of the rectangle relative to the lower left anchor.
pivot
The normalized position in this RectTransform that it rotates around.
rect
The calculated rectangle in the local space of the Transform.
sizeDelta
The size of this RectTransform relative to the distances between the anchors.
乍一看有點費解,這里有必要解釋下:
anchoredPosition
可以理解為Pivot點相對于Anchor reference點的位置。Anchor reference點,我是這樣理解的:當四個anchors點在一起的時候,這個點就是anchor reference點;否則這四個點的中心點就是anchor reference點。
照這個推理,anchorMax和anchorMin的值將影響anchoredPosition的值。具體還需要demo研究來確認。
但可以確定的是,當一個UI元素不需要自動拉伸行為時,用anchoredPosition + sizeDelta來設置位置和大小是比較方便的方法。
anchorMax、anchorMin和Inspector中的意義一致,需要注意的是,當UI元素不需要自動拉伸時,AnchorMax和AnchorMin是相等的。
UI元素需要自動拉伸時,使用anchorMax、anchorMin + offsetMax、offsetMin來設置UI的位置及大小會比較方便。
其中,anchorMax.x == anchorMin.x,height會自動拉伸,width固定不變。
anchorMax.y == anchorMin.y,width會自動拉伸,height固定不變。
不知不覺已過凌晨1點,先介紹到這里。關于uGUI的更多內容,將在后續博文中繼續,敬請期待。