Last active
April 26, 2024 02:23
-
-
Save robin-boucher/79950745d5cfd4b2205ff8f22898e9b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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