UNITY: How to get the coordinates of the SafeArea rect?

5.4k views Asked by At

I am working on a project in Unity for Android Portrait mode. I will constantly be modifying the textures of two RawImages, the catch is that the images must be the same width and height(1080x1080, 800x800) 1080x1079 is wrong. Because a lot of phones nowadays are notched, I'm forced to maintain all the UI Elements inside the SafeArea rect. BUT, I don't know how to get the y coordinate of the SafeArea rect relative to the Display. Here's a photo: Here's a photo

So, I only need to get the y coordinate of the SafeArea rect, by my guesses, for the Phone in the example, the y coordinate should be around 100 pixels height. Thank you in advance.

1

There are 1 answers

0
Happaro On

If you are using UI Scale Mode: Scale with screen size Like in this picture, here is my solution for adaptive RectTransform with your safe area (only Vertical):

using UnityEngine;
using UnityEngine.UI;

    public class MySafeArea : MonoBehaviour
    {
        private CanvasScaler canvasScaler;
        private float bottomUnits, topUnits;
        void Start()
        {
            canvasScaler = FindObjectOfType<CanvasScaler>();
            ApplyVerticalSafeArea();
        }
    
        
        public void ApplyVerticalSafeArea()
        {
            var bottomPixels = Screen.safeArea.y;
            var topPixel = Screen.currentResolution.height - (Screen.safeArea.y + Screen.safeArea.height);
    
            var bottomRatio = bottomPixels / Screen.currentResolution.height;
            var topRatio = topPixel / Screen.currentResolution.height;
    
            var referenceResolution = canvasScaler.referenceResolution;
            bottomUnits = referenceResolution.y * bottomRatio;
            topUnits = referenceResolution.y * topRatio;
    
            var rectTransform = GetComponent<RectTransform>();
            rectTransform.offsetMin = new Vector2(rectTransform.offsetMin.x, bottomUnits);
            rectTransform.offsetMax = new Vector2(rectTransform.offsetMax.x, -topUnits);
        }
    }

Just attach this script to your RectTransform with stretched anchors and enjoy the result