using UnityEngine;
|
|
[ExecuteAlways]
|
[RequireComponent(typeof(RectTransform))]
|
public class SafeAreaUI : MonoBehaviour
|
{
|
|
public const int SafeWidth = 75;
|
public const int SafeBottom = 15; //竖屏下方间隔
|
|
|
RectTransform _Panel;
|
Rect LastRect = new Rect(0, 0, 0, 0);
|
|
RectTransform Panel
|
{
|
get
|
{
|
if (_Panel == null)
|
_Panel = GetComponent<RectTransform>();
|
return _Panel;
|
}
|
}
|
|
void Awake()
|
{
|
Refresh();
|
}
|
|
void Update()
|
{
|
Refresh();
|
}
|
|
void Refresh()
|
{
|
if (LastRect != Panel.rect)
|
ApplySafeArea();
|
}
|
|
public void ApplySafeArea()
|
{
|
Panel.anchorMin = Vector2.zero;
|
Panel.anchorMax = Vector2.one;
|
//竖屏
|
if (Screen.height > Screen.width)
|
{
|
if (Screen.height / Screen.width > 1.8)//宽屏需要适配
|
{
|
//上下各间隔SafeWidth
|
Panel.offsetMin = new Vector2(0, SafeBottom);
|
Panel.offsetMax = new Vector2(0, -SafeWidth);
|
}
|
else
|
{
|
Panel.offsetMin = new Vector2(0, 0);
|
Panel.offsetMax = new Vector2(0, 0);
|
}
|
}
|
else
|
{//横屏
|
if (Screen.width / Screen.height > 1.8)//宽屏需要适配
|
{
|
//两边各间隔SafeWidth
|
Panel.offsetMin = new Vector2(SafeWidth, 0);
|
Panel.offsetMax = new Vector2(-SafeWidth, 0);
|
}
|
else
|
{
|
Panel.offsetMin = new Vector2(0, 0);
|
Panel.offsetMax = new Vector2(0, 0);
|
}
|
}
|
LastRect = Panel.rect;
|
}
|
|
}
|