我正在尝试在UIView
内创建一个非常简单的彩色圆圈,并切出切片或以其他颜色显示,如下所示:
我希望这会非常简单,并且只需要几行代码,因为CAShapeLayer
允许您创建各种形状。但是,这似乎比我想象的要复杂得多,因为在线上几乎没有关于如何执行此操作的有用教程。将第三方库用于如此简单的操作似乎有点过大,所以我更喜欢仅使用UIKit
类的解决方案。有任何想法吗?预先感谢!
答案 0 :(得分:3)
根据此Thread,在更新为swift 4并进行编辑以满足您的需要之后(练习时留界= D)
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let pieChart = PieChart(frame: CGRect(x: self.view.center.x, y: self.view.center.y, width: 300.0, height: 300.0))
pieChart.backgroundColor = UIColor.clear
self.view.addSubview(pieChart)
pieChart.center = self.view.center
}
}
class PieChart : UIView {
override func draw(_ rect: CGRect) {
drawSlice(rect, startPercent: 0, endPercent: 100, color: UIColor.gray)
drawSlice(rect, startPercent: 30, endPercent: 65, color: UIColor.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(Double.pi) * 2 - CGFloat(Double.pi)
let endAngle = endPercent / 100 * CGFloat(Double.pi) * 2 - CGFloat(Double.pi)
let path = UIBezierPath()
path.move(to: center)
path.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
path.close()
path.stroke()
color.setFill()
path.fill()
}
}