Search code examples
iphoneipadcore-animation

Moving an object along a curve in iPhone development


I wanted to animate an image object by moving it along a particular curve. It is not a general or random curve but rather a curve which follows a particular path on screen.

Currently, Im manually specifying the list of x and y co-ordinates of the path along which i want the image object to move by setting its frame each time. This is a laborious process in the sense that im setting the specific x and y coordinates of the path and moving the image along it. Is there a more efficient way to do this?

Is there a way that i can specify,say, just about 15 - 20 points and have a curve traced along those to move the object? Any other way to acheive this? Any help would be much appreciated. Thanks.


Solution

  • You could use a combination of UIBezierPath and CAKeyFrameAnimation. I found a very useful blog post dealing with this subject.

    http://oleb.net/blog/2010/12/animating-drawing-of-cgpath-with-cashapelayer/

    Here's a simplified version of what I used (it just animates the drawing of a square):

    UIBezierPath *customPath = [UIBezierPath bezierPath];
    [customPath moveToPoint:CGPointMake(100,100)];
    [customPath addLineToPoint:CGPointMake(200,100)];
    [customPath addLineToPoint:CGPointMake(200,200)];
    [customPath addLineToPoint:CGPointMake(100,200)];
    [customPath addLineToPoint:CGPointMake(100,100)];
    
    UIImage *movingImage = [UIImage imageNamed:@"foo.png"];
    CALayer *movingLayer = [CALayer layer];
    movingLayer.contents = (id)movingImage.CGImage;
    movingLayer.anchorPoint = CGPointZero;
    movingLayer.frame = CGRectMake(0.0f, 0.0f, movingImage.size.width, movingImage.size.height);
    [self.view.layer addSublayer:movingLayer];
    
    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    pathAnimation.duration = 4.0f;
    pathAnimation.path = customPath.CGPath;
    pathAnimation.calculationMode = kCAAnimationLinear;
    [movingLayer addAnimation:pathAnimation forKey:@"movingAnimation"];