You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
CrowdControl/Assets/UI/modeselection/DeviceSafeArea.cs

101 lines
2.8 KiB
C#

// using System.Collections;
// using System.Collections.Generic;
// using UnityEngine;
//
// public class DeviceSafeArea : MonoBehaviour
// {
// [SerializeField] private RectTransform Panel;
// public Vector4 offsetFromDevice;
// Rect LastSafeArea = new Rect(0, 0, 0, 0);
//
// void Awake()
// {
// Panel ??= GetComponent<RectTransform>();
// Refresh();
// }
//
// void Update()
//
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeviceSafeArea : MonoBehaviour
{
[SerializeField] private RectTransform Panel;
public Vector4 offsetFromDevice = new Vector4(0, 47, 34, 0); // iphone 14 safe area offset
public Vector4 lastOffsetFromDevice;
[Space(5)] public Vector4 offsetFromDeviceLog;
Rect LastSafeArea = new Rect(0, 0, 0, 0);
void Awake()
{
Panel ??= GetComponent<RectTransform>();
lastOffsetFromDevice = offsetFromDevice;
Refresh();
}
void Update()
{
Refresh();
}
[ContextMenu("Refresh")]
public void Refresh()
{
Rect safeArea = GetSafeArea();
if (safeArea != LastSafeArea || (offsetFromDevice != lastOffsetFromDevice))
ApplySafeArea(safeArea);
}
Rect GetSafeArea()
{
return Screen.safeArea;
}
void ApplySafeArea(Rect r)
{
LastSafeArea = r;
#if UNITY_EDITOR
{
lastOffsetFromDevice = offsetFromDevice;
// Add manual offsets
r.x += offsetFromDevice.w; // Left offset
r.width -= offsetFromDevice.w + offsetFromDevice.x; // Right offset
r.y += offsetFromDevice.z; // Bottom offset
r.height -= offsetFromDevice.z + offsetFromDevice.y; // Top offset
}
#endif
// Convert safe area rectangle from absolute pixels to normalized anchor coordinates
Vector2 anchorMin = r.position;
Vector2 anchorMax = r.position + r.size;
anchorMin.x /= Screen.width;
anchorMin.y /= Screen.height;
anchorMax.x /= Screen.width;
anchorMax.y /= Screen.height;
Panel.anchorMin = anchorMin;
Panel.anchorMax = anchorMax;
CalculateMargin(r);
}
void CalculateMargin(Rect safeAreas)
{
float screenWidth = Screen.width;
float screenHeight = Screen.height;
var safeArea = safeAreas;
// Calculate the difference between safe area and screen size
float leftMargin = safeArea.x;
float rightMargin = screenWidth - (safeArea.x + safeArea.width);
float topMargin = screenHeight - (safeArea.y + safeArea.height);
float bottomMargin = safeArea.y;
offsetFromDeviceLog.w = leftMargin;
offsetFromDeviceLog.x = rightMargin;
offsetFromDeviceLog.y = topMargin;
offsetFromDeviceLog.z = bottomMargin;
}
}