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