I am trying to draw a pie chart which will be made up of equal sized segments, each with a different colour. I am basing my code off this SO: Draw a circular segment progress in SWIFT
let circlePath = UIBezierPath(ovalInRect: CGRect(x: 200, y: 200, width: 150, height: 150))
var segments: [CAShapeLayer] = []
let segmentAngle: CGFloat = 1.0 / CGFloat(totalSegments)
for var i = 0; i < totalSegments; i++ {
let circleLayer = CAShapeLayer()
circleLayer.path = circlePath.CGPath
// start angle is number of segments * the segment angle
circleLayer.strokeStart = segmentAngle * CGFloat(i)
//create a gap to show segments
let gapSize: CGFloat = 0.008
circleLayer.strokeEnd = circleLayer.strokeStart + segmentAngle - gapSize
circleLayer.lineWidth = 10
circleLayer.strokeColor = UIColor(red:0, green:0.004, blue:0.549, alpha:1).CGColor
circleLayer.fillColor = UIColor.redColor().CGColor
// add the segment to the segments array and to the view
segments.insert(circleLayer, atIndex: i)
view.layer.addSublayer(segments[i])
}
But using this I wanted to make it so I can colour each segment based on the index value i in the for loop. Initially I just tested with odd or even, but found the fill part would fill the entire circle with the last color used.
I suspect that is because the fill colour fills the entire circle, even though the stroke has a finite start and end. How could I create this same effect but enable separate fill color for each segment?