1. 程式人生 > >UGUI之RectTransform排版

UGUI之RectTransform排版

fse 如果 技術分享 計算 ldr sta 矩形 tor context

往Scroll View裏面添加子元素,並整齊排列

Text last =Instantiate(text,transform.position,transform.rotation).GetComponent<Text>();//生成預制text
last.text = nowText;//設置新對象的文本
Text[] texts = this.transform.GetComponentsInChildren<Text>();//獲取該Scroll View下有多少個text,用於計算新產生text的y值
last.transform.parent=context.transform;//設置text父節點為Scroll View裏面的context

//設置text的錨點框為橫向拉伸對其父節點
last.GetComponent<RectTransform> ().anchorMin = new Vector2 (0, 1);//左下
last.GetComponent<RectTransform> ().anchorMax = new Vector2 (1, 1);//右上

//設置text的大小
last.GetComponent<RectTransform> ().offsetMax = new Vector2 (2, 0);//左下偏移量
last.GetComponent<RectTransform> ().offsetMin = new Vector2 (2, -20);//右上偏移量

last.GetComponent<RectTransform> ().anchoredPosition = new Vector2 (0, -10-(texts.Length)*20);//設置錨點位置(當錨點是一個點的時候就是該點,本例中該錨點框是一條線,所以該點指的這條錨點線的中間,同理如果是矩形時那麽對應的也是該矩形中心)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

還可以直接在context上面加一個GridLayoutGroup組件

技術分享

只需要把對應的每個cell的大小 邊距 配置好 直接往context裏面添加子物體也能達到同樣的效果。

代碼就簡化為:

Text last =Instantiate(text,transform.position,transform.rotation).GetComponent<Text>();
last.text = nowText;

last.transform.parent=context.transform;

所有的排版設置全部都交給GridLayoutGroup完成了

UGUI之RectTransform排版