在 swift 中沿图层的特定路径设置动画

animate along certain path of a layer in swift

我是 iOS 的新手,我面临一个关于 CAKeyframeAnimation 的小问题,我想将视图动画化到另一个视图层的特定路径。它已经成功地制作了动画。但是,动画的位置不是我所期望的。

正如您在我的代码中看到的那样。我创建了一个带有圆形边界的 UIView(myView)。我想要另一个视图(正方形)跟随 myView 边界的轨道。我已经将 myView 的中心设置到屏幕中间。然后我尝试获取 myView 的 CGPath 并将其设置为 CAKeyframeAnimation 的路径。但是,正方形在其他地方旋转,而不是在 myView 的边界上。谁能帮帮我?谢谢

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)    
    let square = UIView()
    square.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
    square.backgroundColor = UIColor.redColor()
    self.view.addSubview(square)
    let bounds = CGRect(x: 0, y: 0, width: 200, height: 200)
    let myView = UIView(frame: bounds)
    myView.center = self.view.center
    myView.layer.cornerRadius = bounds.width/2
    myView.layer.borderWidth = 10
    myView.layer.borderColor = UIColor.brownColor().CGColor
    self.view.addSubview(myView)       
    var orbit = CAKeyframeAnimation(keyPath: "position")
    orbit.path = CGPathCreateWithEllipseInRect(myView.layer.bounds, nil)
    orbit.rotationMode = kCAAnimationRotateAuto
    orbit.repeatCount = Float.infinity
    orbit.duration = 5.0
    square.layer.addAnimation(orbit, forKey: "orbit")
}

frame "describes the view’s location and size in its superview’s coordinate system," 而 bounds "describes the view’s location and size in its own coordinate system."

因此,如果您从 bounds 构建路径,则 square 必须是 myView 的子视图。如果您使用 myViewframe 构建路径,那么 square 可能是 view 的子视图。

所以,我找到了另一个解决方案,我没有根据已经存在的某些视图创建 CGPath,而是使用了

let myPath = UIBezierPath(arcCenter: myView.center, radius: bounds.width/2, startAngle: CGFloat(-(CGFloat(M_PI_2))), endAngle: CGFloat((2.0 * M_PI - M_PI_2)), clockwise: true).CGPath

这样我就可以指定UIBezierPath的中心点了。