using UnityEngine; using PhxhSDK; /// /// 刘海屏适配器,负责处理屏幕适配逻辑 /// 使用组合模式,从UIWindow中提取出屏幕适配功能 /// public class UINotchScreenAdapter { private Transform _rootTransform; private ScreenOrientation _lastOrientation; private Vector2 _offsets; // x,y代表左右的偏移量 private GameObject _goLeft; private GameObject _goRight; // 默认的左右刘海屏节点名称 private const string LEFT_NOTCH_NODE_NAME = "UI_LiuHaiLeft"; private const string RIGHT_NOTCH_NODE_NAME = "UI_LiuHaiRight"; /// /// 构造函数,创建时自动初始化屏幕适配 /// /// 需要进行适配的根节点Transform public UINotchScreenAdapter(Transform rootTransform) { _rootTransform = rootTransform; _lastOrientation = Screen.orientation; InitScreenUIOffset(); UpdateScreenAdaption(); } /// /// 更新检查,需要在Update中调用 /// public void UpdateCheck() { if (_lastOrientation != Screen.orientation) { // 屏幕方向发生变化时更新适配 _lastOrientation = Screen.orientation; UpdateScreenAdaption(); } } /// /// 屏幕适配,目前方案是左右固定名称的节点下的各个物体需要适配,其他的不管 /// private void UpdateScreenAdaption() { if (_goLeft) { var rectTrans = _goLeft.GetComponent(); var originPos = rectTrans.anchoredPosition; rectTrans.anchoredPosition = new Vector2(_offsets.x, originPos.y); } if (_goRight) { var rectTrans = _goRight.GetComponent(); var originPos = rectTrans.anchoredPosition; rectTrans.anchoredPosition = new Vector2(_offsets.y, originPos.y); } } /// /// 设置屏幕偏移量 /// /// 偏移量 private void SetScreenOffsets(Vector2 offset) { _offsets = offset; } /// /// 初始化屏幕UI偏移量 /// private void InitScreenUIOffset() { var offset = DeviceHelper.GetWidthOffset(); _goLeft = _rootTransform.Find(LEFT_NOTCH_NODE_NAME)?.gameObject; if (_goLeft) { var rectTrans = _goLeft.GetComponent(); var originPos = rectTrans.anchoredPosition; SetScreenOffsets(new Vector2(originPos.x + offset.x, 0)); } _goRight = _rootTransform.Find(RIGHT_NOTCH_NODE_NAME)?.gameObject; if (_goRight) { var rectTrans = _goRight.GetComponent(); var originPos = rectTrans.anchoredPosition; SetScreenOffsets(new Vector2(_offsets.x, originPos.x - offset.y)); } } /// /// 获取当前的屏幕偏移量 /// /// 偏移量 public Vector2 GetCurrentOffsets() { return _offsets; } }