Search code examples
iosanimationcakeyframeanimation

CAKeyframeAnimation repeat animation from begin to end


I need to add infinite animation for UIImageView from start point to end point and after that from end point to start point. I am trying like this:

CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
pathAnimation.calculationMode = kCAAnimationPaced;
pathAnimation.fillMode = kCAFillModeForwards;
pathAnimation.removedOnCompletion = NO;
pathAnimation.duration = 2.0;
pathAnimation.repeatCount = HUGE_VALF;
pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

CGPoint endPoint = CGPointMake(320.0f - 30.0f, self.myImage.frame.size.height);
CGMutablePathRef curvedPath = CGPathCreateMutable();
CGPathMoveToPoint(curvedPath, NULL, self.myImage.frame.origin.x, self.myImage.frame.origin.y);
CGPathAddCurveToPoint(curvedPath, NULL, endPoint.x, self.myImage.frame.origin.y,
                      endPoint.x, self.myImage.frame.origin.y, endPoint.x, endPoint.y);
pathAnimation.path = curvedPath;
CGPathRelease(curvedPath);

[self.myImage.layer addAnimation:pathAnimation forKey:@"curveAnimation"];

myImage moves from start point to end ok, but after that move to start point and repeat animation from start point to end. So, There is no animation from end point to start. Is it possible to do?


Solution

  • Animating back the same way as you came is as simple as setting autoreverses to YES.

    That said, If it's truly an infinite animation then you don't need the fillMode or the removedOnCompletion