您将如何快速绘制饼图视图?

Tob*_*ob 1 charts geometry ios swift

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

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)
Run Code Online (Sandbox Code Playgroud)

但是,这不会产生理想的效果,因为它以线性方式而不是围绕中心画圆。

在此处输入图片说明

vac*_*ama 6

您的路径是圆弧,它通过连接端点将其封闭。您希望路径到达圆心。

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

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()
Run Code Online (Sandbox Code Playgroud)

闭合路径会添加从圆心到圆弧起点的直线。这样可以确保完整的饼块被打上。