【问题标题】:Filling UIBezierPath to create pie chart填充 UIBezierPath 以创建饼图
【发布时间】:2021-06-04 12:55:10
【问题描述】:

我正在尝试使用UIBezierPath 创建一个饼图。

问题是当填充时,端点不是在中心连接,而是像这样相互连接:

  func progressCircle() -> CALayer { 
        let progressCircle = CAShapeLayer()
        
        let pi : CGFloat = .pi
        let rect = CGRect(x: 0, y: 0, width: 50, height: 50)
        let radius = rect.width/2
        
        let phaseShift = 1/2*pi
        let current : CGFloat = 70.0//currentCount
        let total : CGFloat = 100.0//total
        let startAngle : CGFloat = 0 - phaseShift
        let endAngle = (2 * pi * current/total) - phaseShift
        

        progressCircle.path = UIBezierPath(arcCenter: CGPoint(x: rect.midX, y: rect.midY), radius:radius , startAngle: startAngle, endAngle: endAngle, clockwise: true).cgPath
        progressCircle.fillColor = UIColor.red.cgColor
        

        return progressCircle
    }

【问题讨论】:

  • 这是您的代码的正常行为。你有分,自己画,不要只靠UIBezierPath(arcCenter:radius:startAngle:endAngle:clockwise:)

标签: swift pie-chart uibezierpath


【解决方案1】:

这是正常行为,因为您使用的是UIBezierPath(arcCenter:radius:startAngle:endAngle:clockwise:)。你不会告诉你的路径回到中心。

不如自己画。

注释行不是必需的,但可以帮助您了解发生了什么。

let bezierPath = UIBezierPath()
let center = CGPoint(x: rect.midX, y: rect.midY)
bezierPath.move(to: center)
//bezierPath.addLine(to: CGPoint(x: center.x + radius * cos(startAngle), y: center.y + radius * sin(startAngle)))
bezierPath.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
//bezierPath.addLine(to: CGPoint(x: center.x + radius * cos(endAngle), y: center.y + radius * sin(endAngle)))
bezierPath.addLine(to: center)
bezierPath.close()

当然,这是糟糕的 ASCII 艺术,但你看到了 3 个“+”,它们是中心,以及两个注释线点以供记录。 中心和这些点之间的线是隐含的,如果要隐含它们,请取消注释。

     +-
     |  `
     |   `
+----+   )
`.       '
 `.     '
  `- - - 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 2020-05-01
    相关资源
    最近更新 更多