Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

CanvasHelper resizes a RectTransform to iPhone X's safe area

Discussion in 'iOS and tvOS' started by _Adriaan, Mar 9, 2018.

  1. _Adriaan

    _Adriaan

    Joined:
    Nov 12, 2009
    Posts:
    463
    Hey everyone,

    I though it would be nice to share this thing I wrote! CanvasHelper will resize a child RectTransform named "SafeArea" to fit Screen.safeArea.



    Make sure to set the SafeArea's anchors to Min(0,0) and Max(1,1)!



    You may also register events to OnResolutionOrOrientationChanged, as Unity itself doesn't have a way for you register to those events. This component should be attached to a Canvas GameObject in every scene in your game.

    Code (CSharp):
    1.  
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Events;
    5.  
    6. [RequireComponent(typeof(Canvas))]
    7. public class CanvasHelper : MonoBehaviour
    8. {
    9.     private static List<CanvasHelper> helpers = new List<CanvasHelper>();
    10.  
    11.     public static UnityEvent OnResolutionOrOrientationChanged = new UnityEvent();
    12.  
    13.     private static bool screenChangeVarsInitialized = false;
    14.     private static ScreenOrientation lastOrientation = ScreenOrientation.Landscape;
    15.     private static Vector2 lastResolution = Vector2.zero;
    16.     private static Rect lastSafeArea = Rect.zero;
    17.  
    18.     private Canvas canvas;
    19.     private RectTransform rectTransform;
    20.     private RectTransform safeAreaTransform;
    21.  
    22.     void Awake()
    23.     {
    24.         if(!helpers.Contains(this))
    25.             helpers.Add(this);
    26.    
    27.         canvas = GetComponent<Canvas>();
    28.         rectTransform = GetComponent<RectTransform>();
    29.    
    30.         safeAreaTransform = transform.Find("SafeArea") as RectTransform;
    31.    
    32.         if(!screenChangeVarsInitialized)
    33.         {
    34.             lastOrientation = Screen.orientation;
    35.             lastResolution.x = Screen.width;
    36.             lastResolution.y = Screen.height;
    37.             lastSafeArea = Screen.safeArea;
    38.    
    39.             screenChangeVarsInitialized = true;
    40.         }
    41.        
    42.         ApplySafeArea();
    43.     }
    44.  
    45.     void Update()
    46.     {
    47.         if(helpers[0] != this)
    48.             return;
    49.    
    50.         if(Application.isMobilePlatform && Screen.orientation != lastOrientation)
    51.             OrientationChanged();
    52.    
    53.         if(Screen.safeArea != lastSafeArea)
    54.             SafeAreaChanged();
    55.    
    56.         if(Screen.width != lastResolution.x || Screen.height != lastResolution.y)
    57.             ResolutionChanged();
    58.     }
    59.  
    60.     void ApplySafeArea()
    61.     {
    62.         if(safeAreaTransform == null)
    63.             return;
    64.    
    65.         var safeArea = Screen.safeArea;
    66.    
    67.         var anchorMin = safeArea.position;
    68.         var anchorMax = safeArea.position + safeArea.size;
    69.         anchorMin.x /= canvas.pixelRect.width;
    70.         anchorMin.y /= canvas.pixelRect.height;
    71.         anchorMax.x /= canvas.pixelRect.width;
    72.         anchorMax.y /= canvas.pixelRect.height;
    73.    
    74.         safeAreaTransform.anchorMin = anchorMin;
    75.         safeAreaTransform.anchorMax = anchorMax;
    76.     }
    77.  
    78.     void OnDestroy()
    79.     {
    80.         if(helpers != null && helpers.Contains(this))
    81.             helpers.Remove(this);
    82.     }
    83.  
    84.     private static void OrientationChanged()
    85.     {
    86.         //Debug.Log("Orientation changed from " + lastOrientation + " to " + Screen.orientation + " at " + Time.time);
    87.    
    88.         lastOrientation = Screen.orientation;
    89.         lastResolution.x = Screen.width;
    90.         lastResolution.y = Screen.height;
    91.  
    92.         OnResolutionOrOrientationChanged.Invoke();
    93.     }
    94.  
    95.     private static void ResolutionChanged()
    96.     {
    97.         //Debug.Log("Resolution changed from " + lastResolution + " to (" + Screen.width + ", " + Screen.height + ") at " + Time.time);
    98.    
    99.         lastResolution.x = Screen.width;
    100.         lastResolution.y = Screen.height;
    101.  
    102.         OnResolutionOrOrientationChanged.Invoke();
    103.     }
    104.  
    105.     private static void SafeAreaChanged()
    106.     {
    107.         // Debug.Log("Safe Area changed from " + lastSafeArea + " to " + Screen.safeArea.size + " at " + Time.time);
    108.    
    109.         lastSafeArea = Screen.safeArea;
    110.    
    111.         for (int i = 0; i < helpers.Count; i++)
    112.         {
    113.             helpers[i].ApplySafeArea();
    114.         }
    115.     }
    116. }
    117.  
    118.  
     
    Last edited: Jun 11, 2020
    Hoorza, Stream, SlimeProphet and 26 others like this.
  2. turnipinrut

    turnipinrut

    Joined:
    Oct 27, 2014
    Posts:
    10
    yeahhhhh boiiiii, you just saved me some hours, thanks!
     
  3. Cadir

    Cadir

    Joined:
    Dec 18, 2016
    Posts:
    1

    My unity not recognized screen.safeArea.

    Please... Help me
     
  4. _Adriaan

    _Adriaan

    Joined:
    Nov 12, 2009
    Posts:
    463
    Your version of Unity is too old. You need at least 2017.3 I believe.
     
  5. _Adriaan

    _Adriaan

    Joined:
    Nov 12, 2009
    Posts:
    463
    (I just updated the script to be much more elaborate! Enjoy, everyone.)
     
    GameDevBryant likes this.
  6. Nikesh78

    Nikesh78

    Joined:
    Mar 9, 2017
    Posts:
    2
    Hey,

    I want to run my game on full screen of IphoneX, by default it is running in safe area. Can you help me with this?

    Thanks
     
    mohaned1001 likes this.
  7. _Adriaan

    _Adriaan

    Joined:
    Nov 12, 2009
    Posts:
    463
    Anything you put in under the SafeArea transform will adhere to the safearea. Anything under the root of the Canvas will still be fullscreen!
     
    GameDevBryant likes this.
  8. turnipinrut

    turnipinrut

    Joined:
    Oct 27, 2014
    Posts:
    10
    you need to update xcode so that you have the latest ios sdk, that will run unity at full screen on the iphone x
     
  9. squarepixel

    squarepixel

    Joined:
    Jan 29, 2016
    Posts:
    1
    hey ,
    Adriaan
    i implemented the script in the game object i am using unity 2017.3 version and xcode 9.2 . but the still getting the same result of full screen not in safe area
     
  10. _Adriaan

    _Adriaan

    Joined:
    Nov 12, 2009
    Posts:
    463
    - put the script on the GameObject called 'Canvas' (or the GameObject with the Canvas script)
    - add a child RectTransform to that Canvas that is called 'SafeArea', and exactly that.
    - add anything you want to adhere to the safe area as a child to the SafeArea object
     
    dregan likes this.
  11. ATMEthan

    ATMEthan

    Joined:
    Dec 27, 2012
    Posts:
    54
    Last edited: Jun 19, 2018
  12. _Adriaan

    _Adriaan

    Joined:
    Nov 12, 2009
    Posts:
    463
    @ATMEthan I use wantedReferenceResolution to scale my interface (depending on the screen size, in other code). You can remove it from the code if you don't want it.

    As for your second comment; the whole purpose of this script is to account for those pixel insets. Unity added Screen.safeArea to their API, and this script sets the size and position of a child object named 'SafeArea' to that safe area.
     
    dregan likes this.
  13. ATMEthan

    ATMEthan

    Joined:
    Dec 27, 2012
    Posts:
    54
    Thanks for the explanation on the reference resolution. That makes sense. And I figured out how to add margins to the SafeArea; during the anchor min and max calculations. I find it strange that the SafeArea for the iPhone X doesn't include the left and right margins but the layout guidelines warn you not to put content in the margins.(At least content that's meaningful)
     
  14. _Adriaan

    _Adriaan

    Joined:
    Nov 12, 2009
    Posts:
    463
    What Unity's API returns for Screen.safeArea is exactly the safe area (or 'margin' in your words) you must adhere to according to Apple. No need to add more margins. Just don't put any buttons and whatnot outside the SafeArea rect.
     
    dregan likes this.
  15. nickculbertson

    nickculbertson

    Joined:
    Oct 22, 2013
    Posts:
    1
    Works like a charm, thanks _Adriaan!
     
  16. NateReese77

    NateReese77

    Joined:
    Jun 14, 2017
    Posts:
    26
    Super bad ass! thanks for this.

    I was running into a small issue where the UI out of the SafeArea was getting scaled down, but that was fixed by updating wantedReferenceResolution to match our UI Resolution (we've been working in 1080 x 1920).
     
  17. ATMEthan

    ATMEthan

    Joined:
    Dec 27, 2012
    Posts:
    54
    Yes, you are right. My iPhone X simulator was giving me incorrect safe area values which is why I asked about the margins. Now that I have a physical iPhone X out of the box this scrip worked. Thanks for it!
     
  18. mannyvw

    mannyvw

    Joined:
    Jun 29, 2015
    Posts:
    3
    Great work Adriaan, annoyingly seems script is not working for me.

    I added the child RectTransform and added my controls to it ran it up, all good controls appear as they should (albiet with iPhoneX cutout still in the way), but just wanted to make sure i had added them correctly.

    Added the script into base ui canvas. run the app, the controls disappear completely. I renabled your debug line and got the following :-

    ApplySafeArea:

    Screen.orientation: Landscape
    Device.generation: iPhoneX
    Screen.safeArea.position: (132.0, 63.0)
    Screen.safeArea.size: (2172.0, 1062.0)
    Screen.width / height: (2436, 1125)
    canvas.pixelRect.size: (2436.0, 1125.0)
    anchorMin: (0.1, 0.1)
    anchorMax: (0.9, 1.0)
    CanvasHelper:ApplySafeArea()


    Quite new to unity am just trying to fix an existing app to allow for iPhoneX.

    Any ideas ?

    thanks

    Neil

    Untitled.png
     
  19. kgiannak

    kgiannak

    Joined:
    Apr 15, 2018
    Posts:
    1
    This looks promising, but can I combine it with a Canvas Scaler? When I add it, I get a message:

    "Non-root Canvases won't be scaled."
     
  20. adrian-taylor09

    adrian-taylor09

    Joined:
    Dec 22, 2016
    Posts:
    35
    @mannyvw Make your SafeArea rect transform set to "Stretch" in both directions, and make sure the top, left, right and bottom values are all 0... (screenshot attached)
     

    Attached Files:

  21. FlashyGoblin

    FlashyGoblin

    Joined:
    Apr 1, 2017
    Posts:
    23
    This works great, thanks! Is there also a method for getting the entire world to respect the SafeArea? Not just the UI?
     
  22. jdgauchat

    jdgauchat

    Joined:
    Jun 24, 2017
    Posts:
    18
    You thought right! :) Thank you!
     
  23. chandu1994

    chandu1994

    Joined:
    May 24, 2018
    Posts:
    2
    Hello,

    Touch not working when i implement this script and also not set proper resolution in iPad devices.

    How can i resolve this issue??
     
  24. _Adriaan

    _Adriaan

    Joined:
    Nov 12, 2009
    Posts:
    463
    My component has absolutely nothing to do with touch input so that's something you need to resolve yourself. As for iPads; those do not have safe areas yet, so... what is the issue exactly?
     
  25. Firemaw

    Firemaw

    Joined:
    Aug 24, 2015
    Posts:
    47
    Last edited: Oct 15, 2018
  26. InspiredSquare

    InspiredSquare

    Joined:
    Nov 16, 2015
    Posts:
    20
    Hi,
    Is there a way to run whole app under safe area or any app level setting to to force app to run under safe area so i do not need to change every scene.
     
  27. _Adriaan

    _Adriaan

    Joined:
    Nov 12, 2009
    Posts:
    463
    If by 'whole app' you mean every canvas in your game, then no: if you created a canvas in every scene of your game, you probably didn't build your game's structure right. That makes your question a bit off-topic regarding my original post, but to give you a quick answer: you'll want to load your interface 'additive' so that you can have 1 scene with all your interface. See the docs on loading scenes.
     
  28. _Adriaan

    _Adriaan

    Joined:
    Nov 12, 2009
    Posts:
    463
    Hey all: I updated the script by removing the resolution scaling and canvas camera functionality. I guess that stuff is weirdly specific and probably not what any of you were hoping to find in this script ;)
     
  29. rsherzod

    rsherzod

    Joined:
    Oct 30, 2016
    Posts:
    5
    Hey Adrian hi, I am working on UI and I am trying to scale canvas with the screen, when try to scale it from iphone 8(tall-750x1334) to iphone x(tall-1125x2436) resolution, I am having empty spot on top of canvas it is not filling whole screen. I think it is because aspect ratio is different on new x models of iphone, do you have any solution for this.Thank you in advance
     
  30. _Adriaan

    _Adriaan

    Joined:
    Nov 12, 2009
    Posts:
    463
    This is the whole point of the script. Anything under the 'SafeArea' transform will adhere to the safe area, which essentially means that the interface won't be under a notch.

    If you want, for instance, a background image to be fullscreen - even outside the safe area - then put it under the Canvas object, and not the SafeArea object.
     
  31. Nieles_GH

    Nieles_GH

    Joined:
    Jun 26, 2017
    Posts:
    56
    Thanks for the script. I found however that the script was a little over complicated and the safe area wasn't updated when rotating the phone because you compared safeArea.size, which stays the same when you rotate the phone. So instead I compare the entire rect.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. [RequireComponent(typeof(Canvas))]
    6. public class CanvasSafeArea : MonoBehaviour
    7. {
    8.     public RectTransform SafeAreaRect;
    9.  
    10.     private Rect lastSafeArea = Rect.zero;
    11.     private Canvas canvas;
    12.  
    13.     private void Awake()
    14.     {
    15.         canvas = GetComponent<Canvas>();
    16.     }
    17.  
    18.     private void Update()
    19.     {
    20.         if (lastSafeArea != Screen.safeArea)
    21.         {
    22.             lastSafeArea = Screen.safeArea;
    23.             ApplySafeArea();
    24.         }
    25.     }
    26.    
    27.     void Start()
    28.     {
    29.         lastSafeArea = Screen.safeArea;
    30.         ApplySafeArea();
    31.     }
    32.  
    33.     void ApplySafeArea()
    34.     {
    35.         if (SafeAreaRect == null)
    36.         {
    37.             return;
    38.         }
    39.  
    40.         Rect safeArea = Screen.safeArea;
    41.  
    42.         Vector2 anchorMin = safeArea.position;
    43.         Vector2 anchorMax = safeArea.position + safeArea.size;
    44.         anchorMin.x /= canvas.pixelRect.width;
    45.         anchorMin.y /= canvas.pixelRect.height;
    46.         anchorMax.x /= canvas.pixelRect.width;
    47.         anchorMax.y /= canvas.pixelRect.height;
    48.  
    49.         SafeAreaRect.anchorMin = anchorMin;
    50.         SafeAreaRect.anchorMax = anchorMax;
    51.     }
    52. }
    53.  
     
  32. _Adriaan

    _Adriaan

    Joined:
    Nov 12, 2009
    Posts:
    463
    Good point, I'll update the script.

    The 'complicated' code mostly makes sure you can have multiple canvases, which is pretty common for most games I've seen or worked on.
     
    Last edited: Mar 10, 2019
  33. Ben-BearFish

    Ben-BearFish

    Joined:
    Sep 6, 2011
    Posts:
    1,204
    @_Adriaan If I wanted to update the Camera.pixelRect to render to the Screen.safeArea, do you know how to do that?
     
  34. _Adriaan

    _Adriaan

    Joined:
    Nov 12, 2009
    Posts:
    463
    I wouldn't know this, sorry!
     
  35. Ben-BearFish

    Ben-BearFish

    Joined:
    Sep 6, 2011
    Posts:
    1,204
    No problem. Just been going through all the Screen.safeArea threads and asking around to see if anyone had any info. Thanks for the response.
     
  36. AM-Dev

    AM-Dev

    Joined:
    Aug 5, 2015
    Posts:
    31
    Hi @_Adriaan,
    thanks for sharing the script. Nobody asked, but I wanted to make sure that it works on all newer iPhones. I've got an iPhoneX, but not the iPhone XR, XS and XS Max. Does the safe area work on all devices?
    Thanks!
     
  37. FinalDaniel

    FinalDaniel

    Joined:
    Mar 29, 2017
    Posts:
    12
    Hi @_Adriaan,

    I am pretty sure there is a serious bug in this code - specifically, the y-axis is inverted. I think the safe area rect unity returns has the (x,y) in the top left of the rect, but this layout code assumes it is in the bottom left. ( for example, on and android device with a notch at the top of the screen, a debug log shows the safe area to be (0, 100, 1080, 1820 )

    I had built a safe area UI system based on this and a few samples found online, but found that when I tested it on an android device with a notch at the top of the screen it placed the 'gap' for the notch at the bottom of the screen.

    After a bit more testing on the xCode emulator, it turned out the same thing on the iPhoneX, but it is almost impossible to tell by eye as the iPhone X has spaces on the top and bottom of the screen that are very similar in size.

    I already have some of this code live in a few apps, and I needed a quick fix so I am adding this to the safe area rect I am getting back from Unity:

    // #TEMP_FIX - Invert Y-Axis of Safe Area Rect
    float newY = Screen.height - safeArea.height - safeArea.y;
    safeArea.y = newY;

    I will eventually refactor my code to work off the safe area properly, but I needed a fix ASAP and this was quick...
     
  38. HonorableDaniel

    HonorableDaniel

    Joined:
    Feb 28, 2007
    Posts:
    2,970
    Seems like this would work:
    Code (CSharp):
    1. camera.pixelRect = Screen.safeArea;
     
  39. Ben-BearFish

    Ben-BearFish

    Joined:
    Sep 6, 2011
    Posts:
    1,204
    I already tried that. It doesn't work on iPhone X. So not sure if something's off or wrong with Unity's Screen.safeArea for iPhone X, but I found a more native Objective-C solution.
     
  40. geganadiradze

    geganadiradze

    Joined:
    Sep 23, 2017
    Posts:
    8
    I use Xiaomi mi a2 lite and get similar results, I'm able to fix it by inverting y axis too.

    EDIT:
    Turns out it's bug in 2018.3
     
    Last edited: Apr 25, 2019
  41. JustAnotherDude

    JustAnotherDude

    Joined:
    Oct 28, 2013
    Posts:
    220
    Hi @_Adriaan, I didn't want to derail the other thread, but yours is exactly the script I was talking about, that changing quality breaks it during gameplay because Unity returns 0 width and 0 height when changing quality settings...

    On your update method I had to change this :

    Code (CSharp):
    1.             if (ScreenSafeArea.size != lastSafeArea)
    2.             {
    3.                 SafeAreaChanged();
    4.             }
    to this:

    Code (CSharp):
    1.             if (ScreenSafeArea.size != lastSafeArea && ScreenSafeArea.size.x > 1f && ScreenSafeArea.size.y > 1f)
    2.             {
    3.                 SafeAreaChanged();
    4.             }
    ScreenSafeArea being just a property I have :

    Code (CSharp):
    1.     public static Rect ScreenSafeArea
    2.     {
    3.         get
    4.         {
    5. #if UNITY_EDITOR
    6.             if (emulateIPhoneX)
    7.             {
    8.                 return new Rect(132, 63, 2172, 1062);
    9.             }
    10. #endif
    11.  
    12.             return Screen.safeArea;
    13.         }
    14.     }
    Tested on a Samsung J5 and Unity 2019.1.1f1.

    I attached my test project, this only happened when running on a Android device (didn't happen on my ipad).

    Before you test it comment this part of the test on CanvasHelper.cs line 98 :
    Code (CSharp):
    1. && ScreenSafeArea.size.x > 1f && ScreenSafeArea.size.y > 1f
    Then just build and run the project and click to change between medium, high and very high and it should randomly disappear.

    I really don't understand why, but it completely breaks the canvas here.

    Uncomment the piece of code above and it no longer disappears.
     

    Attached Files:

  42. _Adriaan

    _Adriaan

    Joined:
    Nov 12, 2009
    Posts:
    463
    This is very clearly a Unity bug, and not a bug from my script. Best submit a bug report to Unity to get this fixed ASAP.
     
  43. danthewahl

    danthewahl

    Joined:
    Jul 23, 2017
    Posts:
    1
    Hey Adriaan. I am having an issue with the script where it seems like it is positioning the buttons correctly, but they are expanding in size and overlapping each other for iPhone X. Do you know a workaround for this? I'll attach a pic on iPhone 8 (the way it should look) and the overlapping on iPhone X.

    Image 6-13-19 at 11.59 PM.jpg

    Image 6-14-19 at 12.01 AM.jpg
     

    Attached Files:

  44. _Adriaan

    _Adriaan

    Joined:
    Nov 12, 2009
    Posts:
    463
    This is beside the point of my script, but it probably has something to do with the way the canvas scaler scales your UI elements up or down. There are thousands of ways to avoid it or deal with it, so play around with it!
     
  45. Quartsik

    Quartsik

    Joined:
    Aug 9, 2015
    Posts:
    2
    Good job, thank you!
     
  46. Gurosoft

    Gurosoft

    Joined:
    Sep 14, 2017
    Posts:
    7
    Hello I with all testing I have the same problems.
    When nothc is TOP position safeArea be wrong
    because if I have screen like (1080,1920)
    And Top notch my safe area rect will be (0,0,1080,1728)
    Then Start top and but canvas to top!

    Same with bottom notch...but for bottom "it is ok" because this problem.

    Any solve to move right this safe area rect?
    upload_2019-9-5_11-41-3.png
     
  47. shanecelis

    shanecelis

    Joined:
    Mar 26, 2014
    Posts:
    10
    This code was very helpful and workable. I found an open source project[1] that provides similar functionality with some extra functionality like preview cutouts in the editor.

    [1]: https://github.com/5argon/NotchSolution
     
    Aranda and niknakgames like this.
  48. chrisrcisme

    chrisrcisme

    Joined:
    Jul 7, 2014
    Posts:
    15
    Great script by the way! :)
    Also, I'm not sure if its been point out yet but when using Galaxy A70 the resolution changes from 2324 on x to 2400 or the other way round from some testing I have done last night so the ResolutionChanged() function should include some specific mobile makes and models.
     
  49. drorriov

    drorriov

    Joined:
    Jun 7, 2014
    Posts:
    42
    Thanks for sharing this script!
    Since I use the same project for android and ios with the same canvas I used #if UNITY_IOS since I don't need it for android.
    The only thing left is to test it works for iPhone X/XS etc.. Is there a way to check it within the editor?
     
  50. _Adriaan

    _Adriaan

    Joined:
    Nov 12, 2009
    Posts:
    463
    1. Android also has phones with notches and safe areas, so you shouldn't only need this for iOS.
    2. Unity recently gave a talk about a preview thing they're making that will give you a nice device preview. Video here:



    (also includes a Unity employee using CanvasHelper!)
     
    Last edited: Dec 8, 2019
unityunity