UNITY NGUI IPHONEX完美适配
苹果的IphoneX新增一个安全区的概念,如下图
图中绿色区域为安全区,所有可交互的组件全部放在安全区内,只有背景可以延伸出去,达到全面屏的效果
我们适配IphoneX采用NGUI通用的锚点去适配。默认的NGUI屏幕适配方案不支持安全区这个概念,我在NGUI每个继承UIRect的组件下新增一个Bool变量InSafeArea,这个变量如果为True则表示这个组件是放置在安全区内的,如果为false则表示这个组件是全屏的,一般为True,只有背景图才需要去掉这个勾
原理:
所有的NGUI锚点的适配最终都会调用NGUITools.GetSides这个方法,这个方法实际上是NGUI为Camera写的扩展方法,如下,新增了一个inSafeArea参数,备注内是我新增的
static public Vector3[] GetSides (this Camera cam, float depth, Transform relativeTo, bool inSafeArea = true) { #if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 if (cam.isOrthoGraphic) #else if (cam.orthographic) #endif { // for iphonex by xiaobai float xOffset = 1f; float yOffset = 1f; #if UNITY_IOS //iphone x 适配 if (SystemInfo.deviceModel.Contains("iPhone10,3") || SystemInfo.deviceModel.Contains("iPhone10,6") && inSafeArea) { xOffset = 734f / 812f; yOffset = 340f / 375f; } #elif UNITY_EDITOR //测试代码 if (inSafeArea) { Vector2 ssize = screenSize; if (ssize.x == 1624f && ssize.y == 750f) //自动识别 { xOffset = 734f / 812f; yOffset = 340f / 375f; } } #endif // end for iphonex by xiaobai float os = cam.orthographicSize; float x0 = -os * xOffset; float x1 = os * xOffset; float y0 = -os * yOffset; float y1 = os; Rect rect = cam.rect; Vector2 size = screenSize; float aspect = size.x / size.y; aspect *= rect.width / rect.height; x0 *= aspect; x1 *= aspect; // We want to ignore the scale, as scale doesn"t affect the camera"s view region in Unity Transform t = cam.transform; Quaternion rot = t.rotation; Vector3 pos = t.position; mSides[0] = rot * (new Vector3(x0, 0f, depth)) + pos; mSides[1] = rot * (new Vector3(0f, y1, depth)) + pos; mSides[2] = rot * (new Vector3(x1, 0f, depth)) + pos; mSides[3] = rot * (new Vector3(0f, y0, depth)) + pos; } else { mSides[0] = cam.ViewportToWorldPoint(new Vector3(0f, 0.5f, depth)); mSides[1] = cam.ViewportToWorldPoint(new Vector3(0.5f, 1f, depth)); mSides[2] = cam.ViewportToWorldPoint(new Vector3(1f, 0.5f, depth)); mSides[3] = cam.ViewportToWorldPoint(new Vector3(0.5f, 0f, depth)); } if (relativeTo != null) { for (int i = 0; i < 4; ++i) mSides[i] = relativeTo.InverseTransformPoint(mSides[i]); } return mSides; }
原理是如果检测到机型为iphonex,并且锚点限制在安全区内,就自动将屏幕大小缩小为安全区大小,否则就全屏。为了方便测试 在编辑器下,设置分辨率为1624x750就可以方便的看到iphonex的效果了
这段代码只展示原理,具体如何去应用,还需要改动UIRect和UIRectEditor的相关方法
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。