uGUI之AutoLayout詳解——minHeight,preferredHeight,flexibleHeight

首先看一個(gè)例子,新建一個(gè)Panel吱七,在下面添加兩個(gè)Button,分別命名為Button鹤竭、Button2踊餐。
1、給Panel添加一個(gè)VerticalLayoutGroup組件臀稚,ChildForceExpand屬性中勾上Width吝岭。
2、給Button吧寺、Button2添加LayoutElement組件窜管,其中Button的FlexibleHeight設(shè)置為0.3,Button2的FlexibleHeight設(shè)置為0.1
3稚机、將Panel的高度設(shè)置為100

1-1
1-2

這時(shí)我們發(fā)現(xiàn)幕帆,Button的高度是70,Button2的高度是30赖条。奇怪失乾,這個(gè)高度是怎么算出來的呢?

網(wǎng)上搜索一番纬乍,竟然很少有人討論uGUI的AutoLayout碱茁,尤其是flexibleWidth/Height屬性的意義,官方文檔也語焉不詳仿贬。這時(shí)只能放大招了纽竣,uGUI已經(jīng)開源,索性把代碼拉下來看看到底怎么實(shí)現(xiàn)的茧泪。下面是托管代碼的地址:
https://bitbucket.org/Unity-Technologies/ui

uGUI的AutoLayout有三個(gè)核心接口退个,定義在ILayoutElement.cs文件中:
ILayoutElement
ILayoutController
ILayoutIgnorer

結(jié)構(gòu)很清晰,由ILayoutElement提供布局信息调炬,ILayoutController來控制布局语盈,ILayoutIgnore提供給UI忽略AutoLayout的能力。

例子中使用的VerticalLayoutGroup繼承自HorizontalOrVerticalLayoutGroup缰泡,這個(gè)類實(shí)現(xiàn)了布局的核心邏輯刀荒,代碼量不多,我就直接貼上來了

protected void CalcAlongAxis(int axis, bool isVertical)
{
    float combinedPadding = (axis == 0 ? padding.horizontal : padding.vertical);

    float totalMin = combinedPadding;
    float totalPreferred = combinedPadding;
    float totalFlexible = 0;

    bool alongOtherAxis = (isVertical ^ (axis == 1));
    for (int i = 0; i < rectChildren.Count; i++)
    {
        RectTransform child = rectChildren[i];
        float min = LayoutUtility.GetMinSize(child, axis);
        float preferred = LayoutUtility.GetPreferredSize(child, axis);
        float flexible = LayoutUtility.GetFlexibleSize(child, axis);
        if ((axis == 0 ? childForceExpandWidth : childForceExpandHeight))
            flexible = Mathf.Max(flexible, 1);

        if (alongOtherAxis)
        {
            totalMin = Mathf.Max(min + combinedPadding, totalMin);
            totalPreferred = Mathf.Max(preferred + combinedPadding, totalPreferred);
            totalFlexible = Mathf.Max(flexible, totalFlexible);
        }
        else
        {
            totalMin += min + spacing;
            totalPreferred += preferred + spacing;

            // Increment flexible size with element's flexible size.
            totalFlexible += flexible;
        }
    }

    if (!alongOtherAxis && rectChildren.Count > 0)
    {
        totalMin -= spacing;
        totalPreferred -= spacing;
    }
    totalPreferred = Mathf.Max(totalMin, totalPreferred);
    SetLayoutInputForAxis(totalMin, totalPreferred, totalFlexible, axis);
}

protected void SetChildrenAlongAxis(int axis, bool isVertical)
{
    float size = rectTransform.rect.size[axis];

    bool alongOtherAxis = (isVertical ^ (axis == 1));
    if (alongOtherAxis)
    {
        float innerSize = size - (axis == 0 ? padding.horizontal : padding.vertical);
        for (int i = 0; i < rectChildren.Count; i++)
        {
            RectTransform child = rectChildren[i];
            float min = LayoutUtility.GetMinSize(child, axis);
            float preferred = LayoutUtility.GetPreferredSize(child, axis);
            float flexible = LayoutUtility.GetFlexibleSize(child, axis);
            if ((axis == 0 ? childForceExpandWidth : childForceExpandHeight))
                flexible = Mathf.Max(flexible, 1);

            float requiredSpace = Mathf.Clamp(innerSize, min, flexible > 0 ? size : preferred);
            float startOffset = GetStartOffset(axis, requiredSpace);
            SetChildAlongAxis(child, axis, startOffset, requiredSpace);
        }
    }
    else
    {
        float pos = (axis == 0 ? padding.left : padding.top);
        if (GetTotalFlexibleSize(axis) == 0 && GetTotalPreferredSize(axis) < size)
            pos = GetStartOffset(axis, GetTotalPreferredSize(axis) - (axis == 0 ? padding.horizontal : padding.vertical));

        float minMaxLerp = 0;
        if (GetTotalMinSize(axis) != GetTotalPreferredSize(axis))
            minMaxLerp = Mathf.Clamp01((size - GetTotalMinSize(axis)) / (GetTotalPreferredSize(axis) - GetTotalMinSize(axis)));

        float itemFlexibleMultiplier = 0;
        if (size > GetTotalPreferredSize(axis))
        {
            if (GetTotalFlexibleSize(axis) > 0)
                itemFlexibleMultiplier = (size - GetTotalPreferredSize(axis)) / GetTotalFlexibleSize(axis);
        }

        for (int i = 0; i < rectChildren.Count; i++)
        {
            RectTransform child = rectChildren[i];
            float min = LayoutUtility.GetMinSize(child, axis);
            float preferred = LayoutUtility.GetPreferredSize(child, axis);
            float flexible = LayoutUtility.GetFlexibleSize(child, axis);
            if ((axis == 0 ? childForceExpandWidth : childForceExpandHeight))
                flexible = Mathf.Max(flexible, 1);

            float childSize = Mathf.Lerp(min, preferred, minMaxLerp);
            childSize += flexible * itemFlexibleMultiplier;
            SetChildAlongAxis(child, axis, pos, childSize);
            pos += childSize + spacing;
        }
    }
}

其中SetChildrenAlongAxis方法清晰地闡釋了minHeight,preferredHeight,flexibleHeight的涵義棘钞。

為了幫助理解缠借,我們先定義幾個(gè)概念。我們把當(dāng)前UI所有同級并參與自動布局的組件的preferredHeight總和稱為totalPreferredHeight宜猜,minHeight的總和稱為totalMinHeight泼返,父UI的真實(shí)高度稱為realHeight∫逃担總結(jié)如下:

1绅喉、minHeight
在自動布局中渠鸽,此UI最小高度不會小于minHeight。這個(gè)參數(shù)定義了realHeight < totalMinHeight時(shí)柴罐,當(dāng)前子UI的height為minHeight徽缚。

2、preferredHeight
可以理解為革屠,UI自身希望的高度凿试。
當(dāng)totalMinHeight < realHeight < totalPreferredHeight時(shí),realHeight處于totalMinHeight和totalPreferredHeight之間一定百分比似芝,把這個(gè)比例應(yīng)用到每一個(gè)接受自動布局的子UI上那婉,即是我們最終得到的效果

1-3

3、flexibleHeight
當(dāng)realHeight > totalPreferredHeight時(shí)党瓮,父UI會剩下一部分高度详炬。flexibleHeight就是告訴AutoLayout系統(tǒng),應(yīng)該怎么瓜分剩下的高度麻诀,使子UI填充滿父UI痕寓。flexibleHeight默認(rèn)是-1,不會進(jìn)行擴(kuò)充蝇闭。當(dāng)flexibleHeight > 0時(shí)呻率,flexibleHeight值作為權(quán)重來計(jì)算當(dāng)前子UI最終的高度,公式如下:

height = preferredHeight + (flexibleHeight / totalFlexibleHeight) * (realHeight - totalPreferredHeight)

flexibleHeight示意圖

弄清楚這些概念后呻引,我們再看一下文章開頭的例子礼仗。
button1的flexibleHeight=0.3,button2的flexibleHeight=0.1逻悠,minHeight和preferredHeight都沒有設(shè)置元践,按道理高度應(yīng)該分別是75、25童谒。為什么會出現(xiàn)70单旁、30?

查一下ILayoutElement的實(shí)現(xiàn)類


ILayoutElement實(shí)現(xiàn)類

發(fā)現(xiàn)Image和Text實(shí)現(xiàn)了ILayoutElement饥伊,而我們的按鈕中默認(rèn)是有一個(gè)Image組件的象浑,用腳本獲取這個(gè)Image然后打印它的preferredHeight,發(fā)現(xiàn)等于10
再套用flexibleHeight的計(jì)算公式:
Button1:10 + 0.3/0.4 * (100 - 20) = 70
Button2:10 + 0.1/0.4 * (100 - 20) = 30

這里有個(gè)問題琅豆,一個(gè)GameObject上掛載兩個(gè)ILayoutElement組件愉豺,是怎么決定用哪個(gè)的?這個(gè)可以在LayoutUtility.cs中找到答案:

LayoutUtility.cs

public static float GetLayoutProperty(RectTransform rect, System.Func<ILayoutElement, float> property, float defaultValue, out ILayoutElement source)
{
    source = null;
    if (rect == null)
        return 0;
    float min = defaultValue;
    int maxPriority = System.Int32.MinValue;
    var components = ComponentListPool.Get();
    rect.GetComponents(typeof(ILayoutElement), components);

    for (int i = 0; i < components.Count; i++)
    {
        var layoutComp = components[i] as ILayoutElement;
        if (layoutComp is Behaviour && (!(layoutComp as Behaviour).enabled || !(layoutComp as Behaviour).isActiveAndEnabled))
            continue;

        int priority = layoutComp.layoutPriority;
        // If this layout components has lower priority than a previously used, ignore it.
        if (priority < maxPriority)
            continue;
        float prop = property(layoutComp);
        // If this layout property is set to a negative value, it means it should be ignored.
        if (prop < 0)
            continue;

        // If this layout component has higher priority than all previous ones,
        // overwrite with this one's value.
        if (priority > maxPriority)
        {
            min = prop;
            maxPriority = priority;
            source = layoutComp;
        }
        // If the layout component has the same priority as a previously used,
        // use the largest of the values with the same priority.
        else if (prop > min)
        {
            min = prop;
            source = layoutComp;
        }
    }

    ComponentListPool.Release(components);
    return min;
}

原來LayoutElement有一個(gè)layoutPriority屬性用來決定優(yōu)先級茫因,這個(gè)屬性暫時(shí)還沒有在編輯器中暴露蚪拦,也許后續(xù)版本會加強(qiáng)這方面的能力。
AutoLayout系統(tǒng)會選用優(yōu)先級最高的ILayoutElement里相應(yīng)屬性返回。Image和Text的優(yōu)先級默認(rèn)是0驰贷,LayoutElement默認(rèn)優(yōu)先級是1盛嘿。所以正常情況會使用LayoutElement中的設(shè)置,但我們的例子中饱苟,LayoutElement沒有設(shè)置preferredHeight孩擂,LayoutElement里布局相關(guān)的初始值都是-1狼渊,所以還是使用了Image的preferredHeight:10箱熬。

【結(jié)語】
其實(shí),只要官方文檔描述詳細(xì)一些狈邑,根本沒必要浪費(fèi)時(shí)間去查這個(gè)來龍去脈城须。這幾天在學(xué)習(xí)swift,蘋果人性化的Programming Guide加上iBooks的配合米苹,使得學(xué)習(xí)這門語言真是件輕松愉快的事情糕伐。相比之下,Unity簡直是在虐待開發(fā)者蘸嘶。Unity良瞧、Unreal、Cryengine等最近也為爭市場弄得頭破血流训唱,除了降價(jià)開源提供新特性之外褥蚯,完善文檔也是不容忽視的工作。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末况增,一起剝皮案震驚了整個(gè)濱河市赞庶,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌澳骤,老刑警劉巖歧强,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異为肮,居然都是意外死亡摊册,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進(jìn)店門颊艳,熙熙樓的掌柜王于貴愁眉苦臉地迎上來茅特,“玉大人,你說我怎么就攤上這事籽暇∥轮危” “怎么了?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵戒悠,是天一觀的道長熬荆。 經(jīng)常有香客問我,道長绸狐,這世上最難降的妖魔是什么卤恳? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任累盗,我火速辦了婚禮,結(jié)果婚禮上突琳,老公的妹妹穿的比我還像新娘若债。我一直安慰自己,他們只是感情好拆融,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布蠢琳。 她就那樣靜靜地躺著,像睡著了一般镜豹。 火紅的嫁衣襯著肌膚如雪傲须。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天趟脂,我揣著相機(jī)與錄音泰讽,去河邊找鬼。 笑死昔期,一個(gè)胖子當(dāng)著我的面吹牛已卸,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播硼一,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼累澡,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了欠动?” 一聲冷哼從身側(cè)響起永乌,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎具伍,沒想到半個(gè)月后翅雏,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡人芽,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年望几,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片萤厅。...
    茶點(diǎn)故事閱讀 39,690評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡橄抹,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出惕味,到底是詐尸還是另有隱情楼誓,我是刑警寧澤,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布名挥,位于F島的核電站疟羹,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜榄融,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一参淫、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧愧杯,春花似錦涎才、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至畏邢,卻和暖如春业扒,著一層夾襖步出監(jiān)牢的瞬間检吆,已是汗流浹背舒萎。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留蹭沛,地道東北人臂寝。 一個(gè)月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像摊灭,于是被迫代替她去往敵國和親咆贬。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,577評論 2 353

推薦閱讀更多精彩內(nèi)容