看Unity3D文檔像看國內(nèi)教課書一樣,一些概念,不懂的時候看還是不懂,明白了以后再看,好像也沒有說錯。好幾個做Unity3D的朋友跟我吐槽過U3D的文檔質(zhì)量,相比Apple貼心的技術(shù)文檔相去甚遠。
話雖這么說,權(quán)威的資料當(dāng)然還是官方的,建議先仔細讀一遍,不懂的再往下讀:
http://docs.unity3d.com/Manual/UISystem.html
網(wǎng)上的教程大多泛泛而談,就不吐槽了。好在還找到了一篇比較好的解讀,在此謝謝作者白貓。文章鏈接在下面
http://www.cnblogs.com/whitecat/p/4159815.html
uGUI里面AutoLayout比較特別,我就此詳細描述一下,希望能減少“教科書”的理解障礙。
RectTransform的理解
UI元素有專門的RectTransform組件來描述元素的幾何信息,繼承于Transform,Inspector中其屬性如下圖。

Anchors,錨點
我們首先需要認識Anchors。官網(wǎng)上的圖片很好表達了Andhors的功能,請恕我實踐下拿來主義。




善于觀察的同學(xué)可能已經(jīng)發(fā)現(xiàn),不管什么情況,button的四個頂點到相應(yīng)錨點的相對位置是不變的:

當(dāng)4個錨點都在一起的時候,RectTransform會顯示Pos X,Pos Y,Width,Height四個屬性可供修改。

當(dāng)不在一起的時候,RectTransform可調(diào)整的屬性會有變化。



Anchors的Min和Max分別是正規(guī)化的值(從0到1),表示占父RectTransform的百分比,下圖中AnchorMin=(0.1,0.1) AnchorMax=(0.9,0.9)

Pivot,UI的中心點
UI元素的旋轉(zhuǎn)和縮放是圍繞pivot進行的。RectTransform組件中,Pivot屬性是一個正規(guī)化的二維向量,用來描述中心點在本身矩形大小的位置。默認值為(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點,我是這樣理解的:當(dāng)四個anchors點在一起的時候,這個點就是anchor reference點;否則這四個點的中心點就是anchor reference點。
照這個推理,anchorMax和anchorMin的值將影響anchoredPosition的值。具體還需要demo研究來確認。
但可以確定的是,當(dāng)一個UI元素不需要自動拉伸行為時,用anchoredPosition + sizeDelta來設(shè)置位置和大小是比較方便的方法。
anchorMax、anchorMin和Inspector中的意義一致,需要注意的是,當(dāng)UI元素不需要自動拉伸時,AnchorMax和AnchorMin是相等的。

UI元素需要自動拉伸時,使用anchorMax、anchorMin + offsetMax、offsetMin來設(shè)置UI的位置及大小會比較方便。
其中,anchorMax.x == anchorMin.x,height會自動拉伸,width固定不變。
anchorMax.y == anchorMin.y,width會自動拉伸,height固定不變。
不知不覺已過凌晨1點,先介紹到這里。關(guān)于uGUI的更多內(nèi)容,將在后續(xù)博文中繼續(xù),敬請期待。