在UIBezierPath

时间:2017-09-23 15:58:20

标签: swift

这是我的代码:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    let amountOfViews = 3
    let difference: CGFloat = 360 / CGFloat(amountOfViews)
    for i in 0...amountOfViews - 1{
        print((CGFloat(i) * difference))
        let view2 = UIView()
        view2.translatesAutoresizingMaskIntoConstraints = false
        view2.backgroundColor = .red
        self.view.addSubview(view2)
        NSLayoutConstraint(item: view2, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
        NSLayoutConstraint(item: view2, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0).isActive = true
        NSLayoutConstraint(item: view2, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 0.09, constant: 0).isActive = true
        NSLayoutConstraint(item: view2, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 0.35, constant: 0).isActive = true
    let orbit = CAKeyframeAnimation(keyPath: "position")
    let circlePath = UIBezierPath(arcCenter: self.view.frame.origin, radius: CGFloat(self.view.frame.height * 0.3), startAngle:  CGFloat(i) * difference, endAngle: CGFloat.pi * 2 + CGFloat(i) * difference, clockwise: true)
    orbit.path = circlePath.cgPath
    orbit.duration = 10
    orbit.isAdditive = true
    orbit.repeatCount = Float.greatestFiniteMagnitude
    orbit.calculationMode = kCAAnimationPaced
    orbit.rotationMode = kCAAnimationRotateAuto
    view2.layer.add(orbit, forKey: "orbit")
    }
}

结果如下:

enter image description here

这是印刷品:

0.0
120.0
240.0

对我而言,观点之间的差异应该是正确的,但事实并非如此。视图彼此接触,而它们之间应该具有相等的间距。将amountOfViews设置为4时,结果如下:

enter image description here

这看起来也很奇怪。我怎样才能使它发挥作用?

1 个答案:

答案 0 :(得分:1)

这是度与弧度的问题UIBezierPath需要以弧度为单位的角度值。您的i变量以度为单位。

let radians = (CGFloat(i) * difference) / 180 * CGFloat.pi
let circlePath = UIBezierPath(arcCenter: self.view.frame.origin, radius: CGFloat(self.view.frame.height * 0.3), startAngle: radians, endAngle: CGFloat.pi * 2 + radians, clockwise: true)