你会如何在swift中绘制饼图视图?

时间:2017-03-13 23:19:31

标签: ios swift charts geometry

我目前正在开展一个需要绘制饼图的项目。我试图用核心图形绘制它,而不是使用第三方库。这是绘制饼图的代码。

let circlePath = UIBezierPath(arcCenter: CGPoint(x: self.frame.width/2 + r/8, y: self.frame.height/2 + r/8), radius: r, startAngle: CGFloat(0), endAngle: CGFloat(M_PI * 2 * Double(percent1 / 100)), clockwise: true)
let circlePath2 = UIBezierPath(arcCenter: CGPoint(x: self.frame.width/2 + r/8, y: self.frame.height/2 + r/8), radius: r, startAngle: CGFloat(M_PI * 2 * Double(percent1 / 100)), endAngle: CGFloat(0), clockwise: true)

let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath

let shapeLayer2 = CAShapeLayer()
shapeLayer2.path = circlePath2.cgPath
//change the fill color
shapeLayer.fillColor = UIColor.red.cgColor
shapeLayer2.fillColor = UIColor.blue.cgColor
//you can change the stroke color
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer2.strokeColor = UIColor.blue.cgColor
//you can change the line width
shapeLayer.lineWidth = 3.0

self.layer.addSublayer(shapeLayer)
self.layer.addSublayer(shapeLayer2)

但是,这并不会产生预期的效果,因为它会线性地绘制圆形而不是围绕中心。

enter image description here

1 个答案:

答案 0 :(得分:3)

您的路径是弧线,它通过连接端点来关闭它。您希望路径转到圆圈的中心。

将中心点添加到每个路径并关闭它们:

circlePath.addLine(to: CGPoint(x: view.frame.width/2 + r/8, y: view.frame.height/2 + r/8))
circlePath.close()

circlePath2.addLine(to: CGPoint(x: view.frame.width/2 + r/8, y: view.frame.height/2 + r/8))
circlePath2.close()

关闭路径将添加从圆的中心点到弧的起点的线。这可以确保完整的饼块被抚摸。

相关问题