Search code examples
iphoneanimationuiviewlinear-algebraaffinetransform

How do I translate parabolically?


I'm working on an iPhone app with some simple animation.

I have a view I want to translate, but not along a line. I want to translate it parabolically. Imagine that I am animating a car moving along a curved road.

I know I can set the transform properly to an instance of CGAffineTransform

Problem is, I have no idea how to create the transform. I know how to scale, translate, etc. but how do I translate parabolically? Is it even possible?


Solution

  • To animate along a smooth curve, you'll want to use a CAKeyframeAnimation. In this answer I provide code for a combined animation that moves an image view along a curve, while resizing it and fading it out. The relevant part of that code is as follows:

    // Set up path movement
    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    pathAnimation.calculationMode = kCAAnimationPaced;
    pathAnimation.fillMode = kCAFillModeForwards;
    pathAnimation.removedOnCompletion = NO;
    
    CGPoint endPoint = CGPointMake(480.0f - 30.0f, 40.0f);
    CGMutablePathRef curvedPath = CGPathCreateMutable();
    CGPathMoveToPoint(curvedPath, NULL, viewOrigin.x, viewOrigin.y);
    CGPathAddCurveToPoint(curvedPath, NULL, endPoint.x, viewOrigin.y, endPoint.x, viewOrigin.y, endPoint.x, endPoint.y);
    pathAnimation.path = curvedPath;
    CGPathRelease(curvedPath);
    

    This creates a curve with two control points, one at the origin of the view and the other at the upper-right corner of the the display (in landscape mode). For more on constructing paths, see the Quartz 2D Programming Guide or the Animation Types and Timing Programming Guide.

    To use this animation, you'll need to add it to your view's layer using something like the following:

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