Search code examples
swiftswiftuicore-graphics

Why does path draw towards the opposite direction?


I have the following code snippet that draws a circular sector shape:

struct CircularSector: Shape {
    let centralAngle: Angle
    
    func path(in rect: CGRect) -> Path {
        let radius = min(rect.width, rect.height) / 2
        let center = CGPoint(x: rect.midX, y: rect.midY)
        var path = Path()
        path.addArc(center: center, radius: radius, startAngle: .degrees(0), endAngle: centralAngle, clockwise: true)
        path.addLine(to: center)
        path.closeSubpath()
        return path
    }
}

When I preview it,

struct CircularSector_Previews: PreviewProvider {
    static var previews: some View {
        CircularSector(centralAngle: .degrees(45)).fill(Color.black)
        }
    }
}

instead of a 45° sector clockwise, it draws a 315° sector counterclockwise. Is this the correct behaviour, or did I do something wrong?

enter image description here


Solution

  • It does seem like a bug. (See https://stackoverflow.com/a/57034585/341994 where exactly the same thing happens.) This is not how UIBezierPath behaves over on the UIKit side. If we say, mutatis mutandis:

        let path = UIBezierPath()
        path.addArc(withCenter: center, radius: radius, 
            startAngle: 0, endAngle: .pi/4, clockwise: true)
        path.addLine(to: center)
        path.close()
    

    We get

    enter image description here

    which is just what you are expecting. It's easy to see how to compensate, but it does seem that what you are compensating for is a mistake in the SwiftUI Path implementation.