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.

    var body: some View {
        GeometryReader { proxy in
            Color.orange
                .clipShape(RoundedRectangle(cornerRadius: proxy.safeAreaInsets.bottom))
                .ignoresSafeArea()
                .padding(.leading, 40)
                .overlay(alignment: .bottom) {
                    Divider().ignoresSafeArea()
                }
        }
    }