2017-09-23 36 views
0

这是我的代码:问题设置视图之间相等的间隔在一UIBezierPath

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

这是度数与弧度的问题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)