用切出的圆圈切成圆? iOS Swift 4

时间:2018-07-17 20:46:56

标签: ios swift cashapelayer

我正在尝试在UIView内创建一个非常简单的彩色圆圈,并切出切片或以其他颜色显示,如下所示:

enter image description here

我希望这会非常简单,并且只需要几行代码,因为CAShapeLayer允许您创建各种形状。但是,这似乎比我想象的要复杂得多,因为在线上几乎没有关于如何执行此操作的有用教程。将第三方库用于如此简单的操作似乎有点过大,所以我更喜欢仅使用UIKit类的解决方案。有任何想法吗?预先感谢!

1 个答案:

答案 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()
    }
}

enter image description here