Skip to content

Instantly share code, notes, and snippets.

@robin-boucher
Last active April 26, 2024 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save robin-boucher/79950745d5cfd4b2205ff8f22898e9b4 to your computer and use it in GitHub Desktop.
Save robin-boucher/79950745d5cfd4b2205ff8f22898e9b4 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UTJ
{
// Attach on "stretch" type anchor
public class UISafeArea : MonoBehaviour
{
[SerializeField] private bool constrainX = true;
[SerializeField] private bool constrainY = true;
private void Start()
{
RefreshSafeArea();
}
private void RefreshSafeArea()
{
Rect safeAreaRect = UnityEngine.Device.Screen.safeArea;
Vector2 anchorMin = safeAreaRect.position;
Vector2 anchorMax = safeAreaRect.position + safeAreaRect.size;
anchorMin.x = this.constrainX ? anchorMin.x / UnityEngine.Device.Screen.width : 0f;
anchorMax.x = this.constrainX ? anchorMax.x / UnityEngine.Device.Screen.width : 1f;
anchorMin.y = this.constrainY ? anchorMin.y / UnityEngine.Device.Screen.height : 0f;
anchorMax.y = this.constrainY ? anchorMax.y / UnityEngine.Device.Screen.height : 1f;
RectTransform rectTransform = GetComponent<RectTransform>();
rectTransform.anchorMin = anchorMin;
rectTransform.anchorMax = anchorMax;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment