swiftswiftui

How we can draw a stroke for a custom path in SwiftUI?


I am making a custom path in SwiftUI and fill it with red color, I want to give a border or stroke for my path. How we can do this?

enter image description here

struct ContentView: View
{
    var body: some View
    {
    
    Path { path in
        path.addArc(center: CGPoint(x: 100, y: 300), radius: 200, startAngle: Angle(degrees: -90), endAngle: Angle(degrees: 0), clockwise: false)
    }
    .fill(Color.red)

    
    
}
}

Solution

  • You'll need to stroke and fill the path separately. Here is one way to do it.

    Assign your path to a variable, and then use that to fill it, and then overlay it with the same path stroked. Note: You need to use path.closeSubpath() to close your path, or only the arc will be stroked.

    struct ContentView: View
    {
        var body: some View {
            let path = Path { path in
                path.addArc(center: CGPoint(x: 100, y: 300), radius: 200, startAngle: Angle(degrees: -90), endAngle: Angle(degrees: 0), clockwise: false)
                path.closeSubpath()
            }
            path.fill(Color.red).overlay(path.stroke(Color.black, lineWidth: 2))
        }
    }
    

    enter image description here