0

I'm working on drawing a pie chart using SwiftUI.

My current code is working by drawing a circle with a radius based on the center of the circle, and filling each pie slice with a corresponding color.

However, I am having a problem with the boundaries of each section of the pie chart being drawn as straight lines ("| | |").

What I want is for these boundaries to be drawn in a circular fashion, meaning I want to draw a circle of small radius at the end of each section.

PieChart

My current code looks like this

    private func drawPieSlice(context: GraphicsContext, size: CGSize) {
        let total = data.reduce(0) { $0 + $1.0 }
        let radius = min(size.width, size.height) * 0.4
        let center = CGPoint(x: size.width * 0.5, y: size.height * 0.5)
    
        var startAngle = Angle.zero
        for (value, color) in data {
            let angle = Angle(degrees: 360 * (value / total))
            let endAngle = startAngle + angle
            let path = Path { path in
                path.move(to: center)
                path.addArc(center: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false)
                path.closeSubpath()
            }
            context.fill(path, with: .color(color))
            startAngle = endAngle
        }
    }

How can I solve this problem, and how should I implement drawing a small circle at the beginning and end of each section?

Any suggestions would be appreciated.

Hajime
  • 212
  • 3
  • 13

0 Answers0