UNITY NGUI IPHONEX完美适配

编程入门 行业动态 更新时间:2024-10-08 19:50:06

UNITY NGUI IPHONEX<a href=https://www.elefans.com/category/jswz/34/1770009.html style=完美适配"/>

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_7if (cam.isOrthoGraphic)
#elseif (cam.orthographic)
#endif{// for iphonex by xiaobaifloat 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 xiaobaifloat 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 UnityTransform 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的相关方法


更多推荐

UNITY NGUI IPHONEX完美适配

本文发布于:2023-07-04 09:23:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1022343.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:完美   UNITY   NGUI   IPHONEX

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!