切出切片做圆圈? iOS Swift 4
Make circle with slice cut out? iOS Swift 4
我正在尝试在 UIView
中创建一个非常简单的彩色圆圈,切出一个切片或使用不同的颜色,如下所示:
我预计这会非常简单,只需要几行代码,因为 CAShapeLayer
允许您创建各种形状。然而,这似乎比我想象的要复杂得多,因为网上几乎没有关于如何做到这一点的有用教程。将第三方库用于如此简单的事情似乎有点矫枉过正,因此我更喜欢仅使用 UIKit
类 的解决方案。有任何想法吗?提前致谢!
根据此 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()
}
}
我正在尝试在 UIView
中创建一个非常简单的彩色圆圈,切出一个切片或使用不同的颜色,如下所示:
我预计这会非常简单,只需要几行代码,因为 CAShapeLayer
允许您创建各种形状。然而,这似乎比我想象的要复杂得多,因为网上几乎没有关于如何做到这一点的有用教程。将第三方库用于如此简单的事情似乎有点矫枉过正,因此我更喜欢仅使用 UIKit
类 的解决方案。有任何想法吗?提前致谢!
根据此 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()
}
}