说明
可使用Unity的Device Simulator在编辑器模式下测试UI在各种移动设备上的显示效果。
将下面的脚本挂在顶层UI节点(通常应是一个背景Panel)即可。(有时其后面应还有一个Bg,它不用被限制在安全区内显示)
UiAdaptScreenSafeArea.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(RectTransform))]
public class UiAdaptScreenSafeArea : MonoBehaviour
{
private RectTransform _rectTrans;
private void Start()
{
Init();
AdaptAnchorsValue();
}
private void Init()
{
_rectTrans = GetComponent<RectTransform>();
_rectTrans.anchorMin = Vector2.zero;
_rectTrans.anchorMax = Vector2.one;
_rectTrans.anchoredPosition = Vector2.zero;
_rectTrans.sizeDelta = Vector2.zero;
}
private void AdaptAnchorsValue()
{
var maxWidth = Display.main.systemWidth;
var maxHeight = Display.main.systemHeight;
var safeArea = UnityEngine.Screen.safeArea;
var anchorMin = safeArea.position;
var anchorMax = safeArea.position + safeArea.size;
anchorMin.x /= maxWidth;
anchorMin.y /= maxHeight;
anchorMax.x /= maxWidth;
anchorMax.y /= maxHeight;
_rectTrans.anchorMin = anchorMin;
_rectTrans.anchorMax = anchorMax;
}
}
网友评论