I need to draw pie chart in a view. I have drawn the background path correctly. But when I add progress layers, paths are not drawn properly.
This is the code I use to create layers and add them to the view.
I created a gist also. You can see the full code from there also. MultiColoredPie Gist
private lazy var pathLayers: [PieLayer] = {
guard let data = self.data else { return [] }
var previousPercentage: CGFloat = 0
let sorted = data.sorted(by: { (data1, data2) -> Bool in
return data1.percentage < data2.percentage
})
var layers: [PieLayer] = []
for (index, item) in sorted.enumerated() {
previousPercentage += item.percentage
let layer = PieLayer()
layer.index = index
layer.lineCap = CAShapeLayerLineCap.square
layer.fillColor = nil
layer.strokeColor = item.color.cgColor
layer.strokeEnd = previousPercentage //item.percentage
layer.percentage = previousPercentage //item.percentage
layers.append(layer)
}
return layers
}()
override func layoutSubviews() {
super.layoutSubviews()
self.addShapes()
}
func addShapes() {
shapeLayer.path = commonPath.cgPath
shapeLayer.lineWidth = lineWidth
self.layer.addSublayer(shapeLayer)
for layer in pathLayers.reversed() {
print("\(layer.index) - \(layer.percentage)")
layer.lineWidth = lineWidth
layer.path = commonPath.cgPath
self.layer.addSublayer(layer)
}
}
I create the path with this code,
private var commonPath: UIBezierPath {
get {
let x = self.frame.width/2
let y = self.frame.height/2
let center = CGPoint(x: x, y: y)
let path = UIBezierPath(arcCenter: center, radius: CGFloat(x - lineWidth/2), startAngle: -90.degreesToRadians, endAngle: 270.degreesToRadians, clockwise: true)
path.close()
return path
}
}
Does anyone know why this happens? (and seems it doesn't start from -90)
You should set proper CGLineCap
. You have CGLineCap.square
, but you need CGLineCap.butt
Here is more information on it: CGLineCap
layer.lineCap = CAShapeLayerLineCap.square
layer.lineCap = CAShapeLayerLineCap.butt