微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

填充 UIBezierPath 以创建饼图

如何解决填充 UIBezierPath 以创建饼图

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

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

enter image description here

  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:)。你没有告诉你回到中心的路径。

相反,自己画。

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

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 个“+”,它们是中心,还有两个注释的行点作为记录。 中心和这些点之间的线是隐含的,如果你想隐含它们,取消注释线。

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。