using UnityEngine;
namespace WL.UI
{
///
/// RectTransform 을 기기 Safe Area(노치·홈 인디케이터 제외 영역)에 맞춘다.
/// HUD 루트 패널에 부착한다.
///
[RequireComponent(typeof(RectTransform))]
[DisallowMultipleComponent]
public class SafeAreaFitter : MonoBehaviour
{
[Tooltip("가로 방향에도 Safe Area 를 적용한다")]
[SerializeField] private bool applyHorizontal = true;
[Tooltip("세로 방향에도 Safe Area 를 적용한다")]
[SerializeField] private bool applyVertical = true;
private RectTransform _rt;
private Rect _lastSafeArea = new Rect(0f, 0f, 0f, 0f);
private Vector2Int _lastResolution = Vector2Int.zero;
private void Awake() { _rt = GetComponent(); Apply(); }
private void OnEnable() { Apply(); }
private void Update()
{
if (Screen.safeArea != _lastSafeArea || Screen.width != _lastResolution.x || Screen.height != _lastResolution.y)
Apply();
}
public void Apply()
{
if (_rt == null) _rt = GetComponent();
if (Screen.width <= 0 || Screen.height <= 0) return;
Rect safe = Screen.safeArea;
_lastSafeArea = safe;
_lastResolution = new Vector2Int(Screen.width, Screen.height);
Vector2 min = new Vector2(safe.xMin / Screen.width, safe.yMin / Screen.height);
Vector2 max = new Vector2(safe.xMax / Screen.width, safe.yMax / Screen.height);
if (!applyHorizontal) { min.x = 0f; max.x = 1f; }
if (!applyVertical) { min.y = 0f; max.y = 1f; }
_rt.anchorMin = min;
_rt.anchorMax = max;
_rt.offsetMin = Vector2.zero;
_rt.offsetMax = Vector2.zero;
}
}
}