Search code examples
swiftswiftui

SwiftUI Rounded view corners like device screen


I'd like to make a view with rounded corners that fills the whole screen. And when a horizontal offset is applied to the whole view, the view's corners match that of the devices screen (The views corner curves should look identical to the phone's screen curve). I know how to simply apply a corner radius. But how do I make this match the specific device?

import SwiftUI

struct ContentView: View {
   let cornerRadius: CGFloat = 38.0
   
   var body: some View {
       GeometryReader { geometry in
           ZStack {
               Color.blue // full-screen content here
           }
           .cornerRadius(self.cornerRadius)
           .offset(x: 20) // Example horizontal offset

       }
       .edgesIgnoringSafeArea(.all) // Make sure it fills the entire screen area
   }
}

Solution

  • You could use the height of the bottom safe-area inset as an approximation.

    • On iPads, the approximation is not bad.
    • On newer iPhone devices, it is less than the actual device radius (based on simulator runs). You might want to scale it here, based on some other information you read from the device (such as user interface idiom or full screen height).
    • On an iPhone SE, the corners are square anyway.
    var body: some View {
        GeometryReader { proxy in
            Color.orange
                .clipShape(RoundedRectangle(cornerRadius: proxy.safeAreaInsets.bottom))
                .ignoresSafeArea()
                .padding(.leading, 40)
                .overlay(alignment: .bottom) {
                    Divider().ignoresSafeArea()
                }
        }
    }