Moving an object along a curve in iPhone development

后端 未结 2 1718
北海茫月
北海茫月 2020-12-14 04:20

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.<

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-14 05:23

    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"];
    

提交回复
热议问题