Untitled
unknown
csharp
a year ago
1.8 kB
19
Indexable
using UnityEngine;
using UnityEngine.InputSystem;
/// <summary>
/// Resizes a UI element with a RectTransform to respect the safe areas of the current device.
/// This is particularly useful on an iPhone X, where we have to avoid the notch and the screen
/// corners.
///
/// The easiest way to use it is to create a root Canvas object, attach this script to a game object called "SafeAreaContainer"
/// that is the child of the root canvas, and then layout the UI elements within the SafeAreaContainer, which
/// will adjust size appropriately for the current device./// </summary>
public class SafeAreaFitter : MonoBehaviour
{
private Rect lastSafeArea;
private RectTransform parentRectTransform;
private RectTransform _boardRectTransformReference;
private void Awake()
{
parentRectTransform = this.GetComponentInParent<RectTransform>();
ApplySafeArea();
}
public bool IsSimulator => Touchscreen.current != null && Touchscreen.current.name != "Injected TouchScreen";
private void Update()
{
if (lastSafeArea != Screen.safeArea || IsSimulator)
{
ApplySafeArea();
}
}
private void ApplySafeArea()
{
Rect safeAreaRect = Screen.safeArea;
float scaleRatio = parentRectTransform.rect.width / Screen.width;
var left = safeAreaRect.xMin * scaleRatio;
var right = -(Screen.width - safeAreaRect.xMax) * scaleRatio;
var top = -(Screen.height - safeAreaRect.yMax) * scaleRatio;
var bottom = safeAreaRect.yMin * scaleRatio;
RectTransform rectTransform = GetComponent<RectTransform>();
rectTransform.offsetMin = new Vector2(left, bottom);
rectTransform.offsetMax = new Vector2(right, top);
lastSafeArea = Screen.safeArea;
}
}Editor is loading...
Leave a Comment