以下代码在 XCode iOS Playground 中运行。它创建了一个自定义UIView
类并绘制两个饼图。起始角度和结束角度以整圆的百分比指定。
您可以根据您拥有的数据轻松扩展它以显示更多或更少的切片。
The drawRect
方法创建一条从中心开始的贝塞尔曲线路径,然后添加一个圆弧段,最后闭合该路径以便对其进行填充。
Xcode 10.2.1/Swift 4.2 更新
class PieChart : UIView {
override func draw(_ rect: CGRect) {
drawSlice(rect: rect, startPercent: 0, endPercent: 50, color: .green)
drawSlice(rect: rect, startPercent: 50, endPercent: 75, color: .red)
}
private func drawSlice(rect: CGRect, startPercent: CGFloat, endPercent: CGFloat, color: UIColor) {
let center = CGPoint(x: rect.origin.x + rect.width / 2, y: rect.origin.y + rect.height / 2)
let radius = min(rect.width, rect.height) / 2
let startAngle = startPercent / 100 * CGFloat.pi * 2 - CGFloat.pi
let endAngle = endPercent / 100 * CGFloat.pi * 2 - CGFloat.pi
let path = UIBezierPath()
path.move(to: center)
path.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
path.close()
color.setFill()
path.fill()
}
}
let pieChart = PieChart(frame: CGRect(x: 0.0, y: 0.0, width: 300.0, height: 300.0))
pieChart.backgroundColor = .clear
未命名的早期版本
import UIKit
class PieChart : UIView {
override func drawRect(rect: CGRect) {
drawSlice(rect, startPercent: 0, endPercent: 50, color: UIColor.greenColor())
drawSlice(rect, startPercent: 50, endPercent: 75, color: UIColor.redColor())
}
private func drawSlice(rect: CGRect, startPercent: CGFloat, endPercent: CGFloat, color: UIColor) {
let center = CGPoint(x: rect.origin.x + rect.width / 2, y: rect.origin.y + rect.height / 2)
let radius = min(rect.width, rect.height) / 2
let startAngle = startPercent / 100 * CGFloat(M_PI) * 2 - CGFloat(M_PI)
let endAngle = endPercent / 100 * CGFloat(M_PI) * 2 - CGFloat(M_PI)
let path = UIBezierPath()
path.moveToPoint(center)
path.addArcWithCenter(center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
path.closePath()
color.setFill()
path.fill()
}
}
let pieChart = PieChart(frame: CGRect(x: 0.0, y: 0.0, width: 300.0, height: 300.0))
pieChart.backgroundColor = UIColor.clearColor()