Last Updated: February 25, 2016
·
1.25K
· novalagung

iOS - Parabolic Animation using CoreAnimation

this code is just another example how to create parabolic animation using CoreAnimation CAKeyframeAnimation.

- (void)parabolicAnimationWithCallback:(void(^)())callback {

    [CATransaction begin];

    [CATransaction setCompletionBlock:^{
        CGPoint temp = view1.center;
        view1.center = view2.center;
        view2.center = temp;

        if (callback) callback();
    }];

    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];

    pathAnimation.calculationMode = kCAAnimationPaced;
    pathAnimation.fillMode = kCAFillModeForwards;
    pathAnimation.removedOnCompletion = NO;
    pathAnimation.duration = 1.;

    CGPoint fromPoint  = view1.center;
    CGPoint toPoint = view2.center;

    BOOL isClockwise = YES;

    CGPoint midPoint = CGPointZero;
    midPoint.x = fromPoint.x + ((toPoint.x - fromPoint.x) / 2);
    midPoint.y = fromPoint.y + ((toPoint.x - fromPoint.x) / 2 * (isClockwise ? -1 : 1));

    CGMutablePathRef curvedPath = CGPathCreateMutable();
    CGPathMoveToPoint(curvedPath, NULL, fromPoint.x, fromPoint.y);
    CGPathAddCurveToPoint(curvedPath, NULL, fromPoint.x, fromPoint.y, midPoint.x, midPoint.y, toPoint.x, toPoint.y);
    pathAnimation.path = curvedPath;
    CGPathRelease(curvedPath);

    [view1.layer addAnimation:pathAnimation forKey:@"animateAlongPath"];

    [CATransaction commit];

}