我想画一个局部圆,我在UIViewController中有以下功能,可以在viewDidLoad中调用它:

import UIKit

class ActivityViewController: UIViewController {

    let progress = CGRect(origin: CGPoint(x:  200, y: 200), size: CGSize(width: 100, height: 100))

    override func viewDidLoad() {
        super.viewDidLoad()
        drawSlice(rect: progress, startPercent: 0, endPercent: 50, color: UIColor.blue)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    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.move(to: center)
        path.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
        path.close()
        color.setFill()
        path.fill()
    }


 }

但是,当我执行此代码时,圆环没有出现,我在做什么错?

最佳答案

您必须在要绘制刚刚创建的路径的的位置指定。例如,您可以使用CAShapeLayer并执行以下操作:

    let myLayer = CAShapeLayer()
    myLayer.path = path.cgPath

    //set some property on the layer
    myLayer.strokeColor = UIColor.blue.cgColor
    myLayer.fillColor = UIColor.white.cgColor
    myLayer.lineWidth = 1.0
    myLayer.position = CGPoint(x: 10, y: 10)

    // add the layer to your view's layer !!important!!
    self.layer.addSublayer(myLayer)

然后,您应该看到您的图层!

关于ios - swift 在UIViewController中绘制局部圆,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45234917/

10-09 10:17