Round Specific Corners SwiftUI

前端 未结 4 1708
不思量自难忘°
不思量自难忘° 2020-12-02 09:12

I know you can use .cornerRadius() to round all the corners of a swiftUI view but is there a way to round only specific corners such as the top?

4条回答
  •  误落风尘
    2020-12-02 09:27

    Using as a custom modifier

    You can use it like a normal modifier:

    .cornerRadius(20, corners: [.topLeft, .bottomRight])
    

    Demo

    You need to implement a simple extension on View like this:

    extension View {
        func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
            clipShape( RoundedCorner(radius: radius, corners: corners) )
        }
    }
    

    And here is the struct behind this:

    struct RoundedCorner: Shape {
    
        var radius: CGFloat = .infinity
        var corners: UIRectCorner = .allCorners
    
        func path(in rect: CGRect) -> Path {
            let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            return Path(path.cgPath)
        }
    }
    

    You can also use the shape directly as a clipping mask.


    Sample Project:

提交回复
热议问题