NGUI所見即所得之UIAnchor & UIStretch

   NGUI所見即所得之UIAnchor & UIStretch

       NGUI的Example/Scenes/Example1介紹的主要就是UIRoot,UIAnchor和UIStretch這三個腳本,當然UIRoot是每個UI都會有的(掛在根節點),之前D.S.Qiu也寫過博客介紹過UIRoot(猛點查看)。一直都對NGUI把Unity的單位和像素的轉換和統一都很有疑惑,因之手遊項目要做UI的自適應,就覺得很有必要把UIAnchor和UIStretch深入的研究下。

        UIRoot在D.S.Qiu的第一篇NGUI的文章中介紹了(猛點查看),UIRoot其實就做了一件事情:根據Screen.height和UIRoot.activeHeight的比例來調整UIRoot的loaclScal,從而保證UIWidget(UISprite,UILabel)可以按照其本身的大小進行設置,而不用經過複雜的換算過程。

         UIAnchor和UIStretch處理上的細節很相似,都是先計算參照對象(這個參照對象由Insprector的Container指定,如果沒有選擇,就是Camera)的大小Rect,然後根據參數UIAnchor(Side,relativeOffset,pixelOffset),UIStretch(Style,relativeSize,initialSize,borderPadding)進行調整,最後設置對應的屬性,只不過UIAnchor設置的是transform.position,UIStretch設置的是(width,height)或clipRange等。

 

UIAnchor

        先看下UIAnchor的Inspector界面,感覺很簡單,不會像UIPanel那麼複雜:

        Container:指定Anchor的參照點,如果沒有選擇,則以Camera的pixelRect的區域爲參照面

        Side:Anchor的定位方式

        Relative Offset:相對於Camera,或Container的百分比偏移

        Pixel Offset:像素的偏移

C#代碼  收藏代碼
  1.        /// <summary>  
  2. /// Relative offset value, if any. For example "0.25" with 'side' set to Left, means 25% from the left side.  
  3. /// </summary>  
  4. public Vector2 relativeOffset = Vector2.zero;  
  5.   
  6. /// <summary>  
  7. /// Pixel offset value if any. For example "10" in x will move the widget 10 pixels to the right   
  8. /// while "-10" in x is 10 pixels to the left based on the pixel values set in UIRoot.  
  9. /// </summary>  
  10. public Vector2 pixelOffset = Vector2.zero;  

 Update函數

       UIAnchor的主要功能實現都在Update函數:

C#代碼  收藏代碼
  1. void Update ()  
  2.     {  
  3.         if (mAnim != null && mAnim.enabled && mAnim.isPlaying) return;  
  4.         bool useCamera = false;  
  5.         UIWidget wc = (container == null) ? null : container.GetComponent<UIWidget>();  
  6.         UIPanel pc = (container == null && wc == null) ? null : container.GetComponent<UIPanel>();  
  7.         if (wc != null)  
  8.         {  
  9.             Bounds b = wc.CalculateBounds(container.transform.parent);  
  10.   
  11.             mRect.x = b.min.x;  
  12.             mRect.y = b.min.y;  
  13.   
  14.             mRect.width = b.size.x;  
  15.             mRect.height = b.size.y;  
  16.         }  
  17.         else if (pc != null)  
  18.         {  
  19.             if (pc.clipping == UIDrawCall.Clipping.None)  
  20.             {  
  21.                 // Panel has no clipping -- just use the screen's dimensions  
  22.                 float ratio = (mRoot != null) ? (float)mRoot.activeHeight / Screen.height * 0.5f : 0.5f;  
  23.                 mRect.xMin = -Screen.width * ratio;  
  24.                 mRect.yMin = -Screen.height * ratio;  
  25.                 mRect.xMax = -mRect.xMin;  
  26.                 mRect.yMax = -mRect.yMin;  
  27.             }  
  28.             else  
  29.             {  
  30.                 // Panel has clipping -- use it as the mRect  
  31.                 Vector4 pos = pc.clipRange;  
  32.                 mRect.x = pos.x - (pos.z * 0.5f);  
  33.                 mRect.y = pos.y - (pos.w * 0.5f);  
  34.                 mRect.width = pos.z;  
  35.                 mRect.height = pos.w;  
  36.             }  
  37.         }  
  38.         else if (container != null)  
  39.         {  
  40.             Transform root = container.transform.parent;  
  41.             Bounds b = (root != null) ? NGUIMath.CalculateRelativeWidgetBounds(root, container.transform) :  
  42.                 NGUIMath.CalculateRelativeWidgetBounds(container.transform);  
  43.   
  44.             mRect.x = b.min.x;  
  45.             mRect.y = b.min.y;  
  46.   
  47.             mRect.width = b.size.x;  
  48.             mRect.height = b.size.y;  
  49.         }  
  50.         else if (uiCamera != null)  
  51.         {  
  52.             useCamera = true;  
  53.             mRect = uiCamera.pixelRect;  
  54.         }  
  55.         else return;  
  56.   
  57.         float cx = (mRect.xMin + mRect.xMax) * 0.5f;  
  58.         float cy = (mRect.yMin + mRect.yMax) * 0.5f;  
  59.         Vector3 v = new Vector3(cx, cy, 0f);  
  60.   
  61.         if (side != Side.Center)  
  62.         {  
  63.             if (side == Side.Right || side == Side.TopRight || side == Side.BottomRight) v.x = mRect.xMax;  
  64.             else if (side == Side.Top || side == Side.Center || side == Side.Bottom) v.x = cx;  
  65.             else v.x = mRect.xMin;  
  66.   
  67.             if (side == Side.Top || side == Side.TopRight || side == Side.TopLeft) v.y = mRect.yMax;  
  68.             else if (side == Side.Left || side == Side.Center || side == Side.Right) v.y = cy;  
  69.             else v.y = mRect.yMin;  
  70.         }  
  71.   
  72.         float width = mRect.width;  
  73.         float height = mRect.height;  
  74.   
  75.         v.x += pixelOffset.x + relativeOffset.x * width;  
  76.         v.y += pixelOffset.y + relativeOffset.y * height;  
  77.   
  78.         if (useCamera)  
  79.         {  
  80.             if (uiCamera.orthographic)  
  81.             {  
  82.                 v.x = Mathf.Round(v.x);  
  83.                 v.y = Mathf.Round(v.y);  
  84.   
  85.                 if (halfPixelOffset && mNeedsHalfPixelOffset)  
  86.                 {  
  87.                     v.x -= 0.5f;  
  88.                     v.y += 0.5f;  
  89.                 }  
  90.             }  
  91.   
  92.             v.z = uiCamera.WorldToScreenPoint(mTrans.position).z;  
  93.             v = uiCamera.ScreenToWorldPoint(v);  
  94.         }  
  95.         else  
  96.         {  
  97.             v.x = Mathf.Round(v.x);  
  98.             v.y = Mathf.Round(v.y);  
  99.   
  100.             if (pc != null)  
  101.             {  
  102.                 v = pc.cachedTransform.TransformPoint(v);  
  103.             }  
  104.             else if (container != null)  
  105.             {  
  106.                 Transform t = container.transform.parent;  
  107.                 if (t != null) v = t.TransformPoint(v);  
  108.             }  
  109.             v.z = mTrans.position.z;  
  110.         }  
  111.   
  112.         // Wrapped in an 'if' so the scene doesn't get marked as 'edited' every frame  
  113.         if (mTrans.position != v) mTrans.position = v;  
  114.         if (runOnlyOnce && Application.isPlaying) Destroy(this);  
  115.     }  

       Update的原理很簡單,梳理歸納爲4部分:

                 1)獲取Anchor參照對象的大小Rect以及計算中心點Vector3 v;

                 2)根據Side類型調整v的x,y,z值;

                 3)將v轉換成世界座標

                 4)將v賦給mTrans.position。

        這裏對1)再多說幾句,主要是涉及參照對象的選取問題,用if - else if來篩選的次序是 UIWidget wc , UIPanel pc , GameObject container, Camera uiCamera,如果前者部位null這取前者的大小後面的就不予考慮。

C#代碼  收藏代碼
  1. UIWidget wc = (container == null) ? null : container.GetComponent<UIWidget>();  
  2. container == null && wc == null) ? null : container.GetComponent<UIPanel>();  

 

像素與Unity單位

        之前項目中使用的NGUI版本還是2.6.3,那個版本還沒有pixelOffset,然後爲了實現一個相對便宜就在掛載Anchor的對象下面掛載一個子對象,通過設置子對象的loaclPosition來設置相對偏移:

      這樣用transform.find去查找某一個子對象的時候就會覺得很蛋疼,所以當看到pixelOffset的就覺得沒有必要用offset這層節點了,這可以說是NGUI埋下隱形的坑(很多沒有“愛參考”不思考的開發者,就喜歡照搬別人的東西),之前的項目就是這樣的,看了一堆Offset,完全沒有必要。然後果斷測試就會有以下不同的情況。

      測試之前首先將上面Bottom/Offset的localPosition置0,並修改稿Bottom的UIAnchor的pixelOffset改爲(0,40)

1)當參照對象是Camera時,即Container=null:

但當編輯器的分辨率等於某個值時,又回恢復正常情況:


 

2)把Bottom的父對象UIPanel拖給UIAnchor的Container:

這種情況是沒有問題的:


 

       回過頭看下Update函數中對pixelOffset的使用:

C#代碼  收藏代碼
  1. v.x += pixelOffset.x + relativeOffset.x * width;  
  2. v.y += pixelOffset.y + relativeOffset.y * height;  

        經過反覆的思考,覺得一定是pixelOffset和子對象Offset的localPosition數值的參考系是不一樣的,但最終都是通過mRect來處理的,所以把UIAnchor Rect mRect設置成public,查看mRect的值,上面三個情況對應mRect值分別如下:



      這說明,當mRect.y大於等於800的時候,使用UIAnchor的pixelOffset和使用子對象Offset的localPosition的表現是一致的。但爲什麼指定Container爲UIPanel都不會出現異常情況,只有Camera會出現。再回到Update看下獲取mRect的方法,指定Container時,mRect實際是UIPanel,或UIWideget的像素大小,其實是UIWidget的(width,height),而沒有指定Container情況下,mRect = camera.pixelRect。

      在UIRoot文中,就說過camera.pixelRect其實就是Screen的(width,height),也就是說,camera.pixelRect是會根據顯示器的分辨率動態改變的,而指定Container時,mRect是不會改變的(在介紹UIRoot文中有介紹)。

       在看下pixelOffset的使用(真的是最後一次了):

C#代碼  收藏代碼
  1. v.x += pixelOffset.x + relativeOffset.x * width;  
  2. v.y += pixelOffset.y + relativeOffset.y * height;  

       雖然pixelOffset的值一直沒有變化,但是當mRect = camera.pixelCamera時,mRect是隨着分辨率的變化而變化的,那樣的話pixelOffset佔的權重就會改變了,所以纔會出現上面的偏移異常。

       

解決策略

       在UIAnchor中設置一個參數unitOffset來代替子對象Offset的功能:

C#代碼  收藏代碼
  1. public Vector2 unitOffset = Vector2.zero;  

       然後把設置的值在Update函數的最後加個 mTrans.localPosition += new Vector3(unitOffset.x,unitOffset.y,0);

C#代碼  收藏代碼
  1. void Update()  
  2.        {      
  3.                //省略前面的處理。。。  
  4.                // Wrapped in an 'if' so the scene doesn't get marked as 'edited' every frame  
  5.     if (mTrans.position != v) mTrans.position = v;  
  6.        mTrans.localPosition += new Vector3(unitOffset.x,unitOffset.y,0);  
  7.     if (runOnlyOnce && Application.isPlaying) Destroy(this);  
  8.        }  

        這樣就可以輕鬆取得GameObject樹中Offset一層,之前項目中就有這個一層,我看着就來火,終於幹掉了哈……

 

        還有一個問題:爲什麼當camera.pixelRect.y等於800時,就會恢復正常,這個先看下UIRoot的設置(對UIRoot原理不瞭解請猛擊):

        Manual Height設置爲800,Scaling Style設置爲FixedSize,可以知道UI的放縮參考高度就是 800,即實際UI佈局高度就是800,這裏有點難理解,總之就是當屏幕分辨率高度等於800時,pixelOffset和子對象Offset的localPostion參考點就一致了,實際效果就一樣了。也可以這麼解釋:當mRect = camera.pixelRect 時,pixeloffset的值是相對於camera.pixelRect而言的,在屏幕的呈現是會對着屏蔽的分辨率不同而改變的;而使用子對象Offset的localPosition的參照和UI組件是一致的,所以相對於Contaner的位置是不會改變的。

        回到文中開頭拋出的一個問題——Unity中transfrom的單位和像素的關係,上張圖片,可以知道UI的高度實際高度是800,然後看下Anchor - Top 和Anchor - Bottom的transform的localPostion.y分別是400.5006和-399.4994(圖片如下),發現兩者區間剛好是800,這就說明NGUI的架構中像素座標和Unity的單位是一致的,對等的,即一個Unity單位等於一個像素。

UIStretch

       看下NGUI Example1 的Anchor - Stretch的Inspector面板,發現UIStretch只比UIAnchor多了一個參數,不過從這張圖UISprite的Dimension(紅框標出)的長度始終都是800,不管屏幕如何改變大小,都是800個像素,填充的Tiled圖片個數也是一樣的,這也更加說明了上面提到的一個結論:NGUI中Unity的單位和像素是同一的。

 Update

       UIStretch的Update函數的前面部分跟UIAnchor的Update的前面部分原理是一樣的都是獲取mRect,所以只看後一部分的實現(理解 relativeSize 和 initialSize 的含義和作用):

C#代碼  收藏代碼
  1. void Update()  
  2. {  
  3.                         //.......省略上面的處理  
  4.             float rectWidth = mRect.width;  
  5.             float rectHeight = mRect.height;  
  6.   
  7.             if (adjustment != 1f && rectHeight > 1f)  
  8.             {  
  9.                 float scale = mRoot.activeHeight / rectHeight;  
  10.                 rectWidth *= scale;  
  11.                 rectHeight *= scale;  
  12.             }  
  13.   
  14.             Vector3 size = (mWidget != null) ? new Vector3(mWidget.width, mWidget.height) : mTrans.localScale;  
  15.   
  16.             if (style == Style.BasedOnHeight)  
  17.             {  
  18.                 size.x = relativeSize.x * rectHeight;  
  19.                 size.y = relativeSize.y * rectHeight;  
  20.             }  
  21.             else if (style == Style.FillKeepingRatio)  
  22.             {  
  23.                 // Contributed by Dylan Ryan  
  24.                 float screenRatio = rectWidth / rectHeight;  
  25.                 float imageRatio = initialSize.x / initialSize.y;  
  26.   
  27.                 if (imageRatio < screenRatio)  
  28.                 {  
  29.                     // Fit horizontally  
  30.                     float scale = rectWidth / initialSize.x;  
  31.                     size.x = rectWidth;  
  32.                     size.y = initialSize.y * scale;  
  33.                 }  
  34.                 else  
  35.                 {  
  36.                     // Fit vertically  
  37.                     float scale = rectHeight / initialSize.y;  
  38.                     size.x = initialSize.x * scale;  
  39.                     size.y = rectHeight;  
  40.                 }  
  41.             }  
  42.             else if (style == Style.FitInternalKeepingRatio)  
  43.             {  
  44.                 // Contributed by Dylan Ryan  
  45.                 float screenRatio = rectWidth / rectHeight;  
  46.                 float imageRatio = initialSize.x / initialSize.y;  
  47.   
  48.                 if (imageRatio > screenRatio)  
  49.                 {  
  50.                     // Fit horizontally  
  51.                     float scale = rectWidth / initialSize.x;  
  52.                     size.x = rectWidth;  
  53.                     size.y = initialSize.y * scale;  
  54.                 }  
  55.                 else  
  56.                 {  
  57.                     // Fit vertically  
  58.                     float scale = rectHeight / initialSize.y;  
  59.                     size.x = initialSize.x * scale;  
  60.                     size.y = rectHeight;  
  61.                 }  
  62.             }  
  63.             else  
  64.             {  
  65.                 if (style != Style.Vertical)  
  66.                     size.x = relativeSize.x * rectWidth;  
  67.   
  68.                 if (style != Style.Horizontal)  
  69.                     size.y = relativeSize.y * rectHeight;  
  70.             }  
  71.   
  72.             if (mSprite != null)  
  73.             {  
  74.                 float multiplier = (mSprite.atlas != null) ? mSprite.atlas.pixelSize : 1f;  
  75.                 size.x -= borderPadding.x * multiplier;  
  76.                 size.y -= borderPadding.y * multiplier;  
  77.   
  78.                 if (style != Style.Vertical)  
  79.                     mSprite.width = Mathf.RoundToInt(size.x);  
  80.   
  81.                 if (style != Style.Horizontal)  
  82.                     mSprite.height = Mathf.RoundToInt(size.y);  
  83.   
  84.                 size = Vector3.one;  
  85.             }  
  86.             else if (mWidget != null)  
  87.             {  
  88.                 if (style != Style.Vertical)  
  89.                     mWidget.width = Mathf.RoundToInt(size.x - borderPadding.x);  
  90.   
  91.                 if (style != Style.Horizontal)  
  92.                     mWidget.height = Mathf.RoundToInt(size.y - borderPadding.y);  
  93.   
  94.                 size = Vector3.one;  
  95.             }  
  96.             else if (mPanel != null)  
  97.             {  
  98.                 Vector4 cr = mPanel.clipRange;  
  99.   
  100.                 if (style != Style.Vertical)  
  101.                     cr.z = size.x - borderPadding.x;  
  102.                   
  103.                 if (style != Style.Horizontal)  
  104.                     cr.w = size.y - borderPadding.y;  
  105.                   
  106.                 mPanel.clipRange = cr;  
  107.                 size = Vector3.one;  
  108.             }  
  109.             else  
  110.             {  
  111.                 if (style != Style.Vertical)  
  112.                     size.x -= borderPadding.x;  
  113.                   
  114.                 if (style != Style.Horizontal)  
  115.                     size.y -= borderPadding.y;  
  116.             }  
  117.               
  118.             if (mTrans.localScale != size)  
  119.                 mTrans.localScale = size;  
  120.   
  121.             if (runOnlyOnce && Application.isPlaying) Destroy(this);  
  122. }  

 整體放縮

     分析了 UIStretch 的 Update ,可以知道當 UIStretch 掛載的GameObject,有UIWidget,UISprite,UIPanel 這個幾個腳本是,是不會放縮這個GameObject的子GameObject的,如果要整體放縮的話,就得通過倒數第二行: 

C#代碼  收藏代碼
  1. mTrans.localScale = size;    

       如果 Style 選擇爲 Both ,並且沒有指定Container 且GameObject 上沒有掛載UIWidget,UISprite,UIPanel ,抽出主要的執行代碼:

C#代碼  收藏代碼
  1. void Update()  
  2. {  
  3.                         //省略前面的代碼  
  4.                        else if (uiCamera != null)  
  5.             {  
  6.                 mRect = uiCamera.pixelRect;  
  7.                 if (mRoot != null) adjustment = mRoot.pixelSizeAdjustment;  
  8.             }  
  9.             else return;  
  10.   
  11.             float rectWidth = mRect.width;  
  12.             float rectHeight = mRect.height;  
  13.   
  14.             if (adjustment != 1f && rectHeight > 1f)  
  15.             {  
  16.                 float scale = mRoot.activeHeight / rectHeight;  
  17.                 rectWidth *= scale;  
  18.                 rectHeight *= scale;  
  19.             }  
  20.   
  21.                         //省略 代碼  
  22.                         else  
  23.             {  
  24.                 if (style != Style.Vertical)  
  25.                     size.x = relativeSize.x * rectWidth;  
  26.   
  27.                 if (style != Style.Horizontal)  
  28.                     size.y = relativeSize.y * rectHeight;  
  29.             }  
  30.                         //省略 代碼  
  31.                         if (mTrans.localScale != size)  
  32.                 mTrans.localScale = size;  
  33. }  

       整理下: mTrans.localScale.x = relativeSize.x * rectWidth * mRoot.activeHeight / rectHeight

mTrans.localScale.y = relativeSize.y * rectHeight * mRoot.activeHeight / rectHeight = relativeSize.y * mRoot .activeHeight

       因爲 UIRoot 是基於高度調整 localScale 的 來做放縮的,所以寬度的放縮UIRoot 已經做了,所以只需要將 relativeSize.y 設置爲 1 / mRoot.activeHeight 使 mTrans.localScale.y = 1恆成立。UIRoot 會是高度始終滿屏(UIRoot Style 爲 FixedSize ),但寬度的放縮總是按照高度的放縮比例在放的,所以會出現寬度沒有全部顯示出來,或者左右兩邊有黑邊。

      其實要想做到滿屏(高度和寬度)縮放的效果,其實可以在UIRoot中增加一個 manualWidth 來調整 UIRoot 的localSize.x 的值。

      另外一種做法就是使用UIStretch ,我們只需要通過設置 relativeSize.x = 1 / manualWidth ;relativeSize.y = 1 / mRoot.activeHeight 就能滿屏縮放了,哈哈,搞定了。等等,這樣是滿屏了,但是其他圖片或文字會被拉伸變形,也就是說 UIStretch 只能做到某個單一的組件按比例縮放。

      總之,實際屏幕顯示的寬度 = (Screen.Height / mRoot.acriveHeight * manualHeight > Screen.Width ) ?  Screen.Width :Screen.Height / mRoot.acriveHeight * manualHeight ,就是去兩者中的更小的。所以要做寬度放縮,只要針對實際顯示寬度 和 屏幕寬度(Screen.Width) 來調整 localScale.x 值就行了。 

 

                                                                                                                                                                                         增補於 2013/11/26 19:45

 

      

       

 

                     

 

 

小結:

       本來昨天晚上就想寫的,但是由於心情不好,也還要一些要點沒有相同,所以才拖到現在完成,今天上了半天班(雖然一直都是在NBA的,今天的詹姆斯太牛逼了,看到我心情都好了,18投14中,罰球11中10,39分),有點小不敬業,喫完中飯之後,就開始組織些了,一直寫到現在(花了5個小時),截了好些圖,這篇應該是D.S.Qiu這麼多篇中寫得最暢快最爽的一次,解決之前的疑問。

       和UIRoot一樣,UIAnchor和UIStretch很簡單,但是卻很重要,雖然就幾個參數,但是要完全明白和理解還是需要花點時間的,所以我才寫出來跟大家分享的,NGUI的文章頁寫了幾篇了(點擊查看),轉載註明出處,尊重原創。

 

        如果您對D.S.Qiu有任何建議或意見可以在文章後面評論,或者發郵件([email protected])交流,您的鼓勵和支持是我前進的動力,希望能有更多更好的分享。

        轉載請在文首註明出處:http://dsqiu.iteye.com/blog/1975972

更多精彩請關注D.S.Qiu的博客和微博(ID:靜水逐風) 

       

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章