代码改变世界

NGUI屏幕自适应

2015-10-22 16:42  公子沐沐  阅读(353)  评论(0编辑  收藏  举报

在NGUI的UIRoot里,把Scaling Style (缩放比例类型)设置为Fixed Size On Mobiles   (固定大小在手机)

因为各个手机分辨率不一样,所以,Manual Height这个值就不是固定不变的了。要Screen.width 和Screen.height来动态的计算它的实际高度,动态的修改这个值。

Min/Max inum Height:这就是支持的最大高度,和最小高度一般都是 640 到 1536。

然后,把这个脚本挂到UIRoot上,来实时的计算Manual Height这个值!

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class UIRootExtend : MonoBehaviour {
 5 
 6     public int ManualWidth = 960;
 7     public int ManualHeight = 640;
 8     
 9     private UIRoot _UIRoot;
10     
11     void Awake()
12     {
13         _UIRoot = this.GetComponent<UIRoot>();
14     }
15     
16     void FixedUpdate()
17     {
18         if (System.Convert.ToSingle(Screen.height) / Screen.width > System.Convert.ToSingle(ManualHeight) / ManualWidth)
19             _UIRoot.manualHeight = Mathf.RoundToInt(System.Convert.ToSingle(ManualWidth) / Screen.width * Screen.height);
20         else
21             _UIRoot.manualHeight = ManualHeight;
22     }
23 }
View Code

当然,在设计UI的时候,是要根据设定的ManualWidth和ManualHeight的大小去设计才能起效。