该解决方案通过对刘海区域UI的位置偏移来解决刘海遮挡问题,高度代码解耦合。
使用方法:在UI父节点挂在NotchFit脚本,然后将被遮挡区域,分别放在“leftElements”\“rightElements”集合里,则在界面首次打开及屏幕旋转时会自动添加偏移量。
ios可以依照机型来区分是否刘海,可以参考:https://blog.csdn.net/cordova/article/details/82945154
我这里没有写这么复杂,只是依靠iPhoneX及以后刘海机型都是大于18:9的,所以很容判断出来。
上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class NotchFit : MonoBehaviour { private static Vector2 notchFitOffset = Vector2.zero; public static Vector2 NotchFitOffset { get => notchFitOffset; } private static bool isInitialized = false; [SerializeField] private List<RectTransform> leftElements = new List<RectTransform>(); [SerializeField] private List<RectTransform> rightElements = new List<RectTransform>(); private ScreenOrientation curScreenOrientation = ScreenOrientation.Portrait; private void Update() { SetNotchFit(); } public void SetNotchFit() { InitNotchFitHeight(); DoNotchFit(); } private void InitNotchFitHeight() { if (isInitialized) return; isInitialized = true; #if UNITY_IOS if (Screen.width / (float)Screen.height > 2) { notchFitOffset = new Vector2(88f, 0); } #elif UNITY_ANDROID //TODO #endif } private void DoNotchFit() { if (notchFitOffset == Vector2.zero) return; if ((Screen.orientation == ScreenOrientation.LandscapeLeft || Screen.orientation == ScreenOrientation.Landscape) && curScreenOrientation != ScreenOrientation.LandscapeLeft) { foreach (var element in leftElements) { if (element != null) element.anchoredPosition += notchFitOffset; } if (curScreenOrientation == ScreenOrientation.LandscapeRight) { foreach (var element in rightElements) { if (element != null) element.anchoredPosition += notchFitOffset; } } curScreenOrientation = ScreenOrientation.LandscapeLeft; } else if (Screen.orientation == ScreenOrientation.LandscapeRight && curScreenOrientation != ScreenOrientation.LandscapeRight) { foreach (var element in rightElements) { if (element != null) element.anchoredPosition -= notchFitOffset; } if (curScreenOrientation == ScreenOrientation.LandscapeLeft) { foreach (var element in leftElements) { if (element != null) element.anchoredPosition -= notchFitOffset; } } curScreenOrientation = ScreenOrientation.LandscapeRight; } } } |
- 本文固定链接: http://www.u3d8.com/?p=2011
- 转载请注明: 网虫虫 在 u3d8.com 发表过