【问题标题】:How would you draw a pie chart view in swift?您将如何快速绘制饼图视图?
【发布时间】:2017-03-13 23:19:31
【问题描述】:

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

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)

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

【问题讨论】:

标签: ios swift charts geometry


【解决方案1】:

您的路径是弧线,它通过连接端点来闭合它。您希望路径能到达您的圆心。

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

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()

关闭路径将添加从圆的中心点到圆弧起点的线。这样可以确保绘制完整的饼图。

【讨论】:

  • circlePath.addLine(to: view.center)
  • @LeoDabus,无论出于何种原因,OP 的中心从视图中心偏移了(r/8, r/8)。 OP 应该将中心分配给一个变量,而不是重复它。
  • 这只是对 OP 的建议。您还应该添加circlePath.close() 以关闭饼图路径
  • 谢谢,将行添加到中心解决了问题。
猜你喜欢
  • 2015-04-30
  • 1970-01-01
  • 1970-01-01
  • 2019-01-03
  • 2016-02-29
  • 1970-01-01
  • 2014-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多