DEV Community

iainrough
iainrough

Posted on

iOS Tips Xamarin Forms - Get Safe Area Height

I needed to get the Safe Area height so I could manipulate a screenshot taken on a device. Stack Overflow to the rescue once again.

Yes the project I'm working on has not started the migration to Maui.

Xamarin Forms

Setup the interface.

IGetSafeArea

public interface IGetSafeArea
{
    double GetSafeAreaTop();
    double GetSafeAreaBottom();
}
Enter fullscreen mode Exit fullscreen mode

Xamarin.iOS

Implement the interface and register it.

GetSafeArea.cs

public class GetSafeArea : IGetSafeArea
    {
        public double GetSafeAreaBottom()
        {
            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
                UIWindow window = UIApplication.SharedApplication.Delegate.GetWindow();
                var bottomPadding = window.SafeAreaInsets.Bottom;
                return bottomPadding;
            }
            return 0;
        }

        public double GetSafeAreaTop()
        {
            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
                UIWindow window = UIApplication.SharedApplication.Delegate.GetWindow();
                var topPadding = window.SafeAreaInsets.Top;
                return topPadding;
            }
            return 0;
        }
    }
Enter fullscreen mode Exit fullscreen mode

AppDelegate.cs

 public partial class AppDelegate : FormsApplicationDelegate
    {
       ...
       DependencyService.Register<GetSafeArea>();
       ...
    }
Enter fullscreen mode Exit fullscreen mode

Using It

 if (Device.RuntimePlatform == Device.iOS)
       {
           var safeAreaTop = DependencyService.Get<IGetSafeArea>().GetSafeAreaTop();

       }
Enter fullscreen mode Exit fullscreen mode

References

StackOverFlow

Top comments (0)