3
votes

enter image description hereI am pretty new to iOS, I am facing a small problem about the CAKeyframeAnimation, I want to animate a view to a certain path of another view layer. it is already successfully animating. However, the position of the animation is not what i expected.

As you can see in my code. I create a UIView(myView) with round bounds. I want another view(square) to follow the orbit of myView's bounds. I already set the myView's centre to the middle of the screen. then I try to get the CGPath of myView and set it to CAKeyframeAnimation's path. However, the square is rotate somewhere else, not on the bounds of myView. Could anyone help me? thanks

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")
}
2

2 Answers

2
votes

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

So if you're building the path from bounds, then square would have to be a subview of myView. If you constructed the path using the frame of myView, then square could be a subview of view.

0
votes

So, I find another solution, instead of create the CGPath based on some view already existed, I used

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

in this way, I can specify the centre point of the UIBezierPath.