Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move a UIImageView

What is the best way to move an image along an array of dots?

like image 518
Alex Avatar asked Dec 31 '22 00:12

Alex


1 Answers

My recommended approach would be to wrap the UIImage in a UIImageView and use a CAKeyframeAnimation to animate your UIImageView's layer along a path that passes through your three points:

UIImage *image = [UIImage imageNamed:@"image.png"];
imageView = [[UIImageView alloc] initWithImage:image];
[mainView addSubview:imageView];
// Remember to remove the image view and release it when done with it

CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
pathAnimation.duration = 1.0f;
pathAnimation.calculationMode = kCAAnimationPaced;
pathAnimation.fillMode = kCAFillModeForwards;
pathAnimation.removedOnCompletion = NO;

CGMutablePathRef pointPath = CGPathCreateMutable();
CGPathMoveToPoint(pointPath, NULL, viewOrigin.x, viewOrigin.y);
CGPathAddLineToPoint(pointPath, NULL, point1.x, point1.y);
CGPathAddLineToPoint(pointPath, NULL, point2.x, point2.y);
CGPathAddLineToPoint(pointPath, NULL, point3.x, point3.y);
pathAnimation.path = pointPath;
CGPathRelease(pointPath);

[imageView.layer addAnimation:pathAnimation forKey:@"pathAnimation"];

Note that by default, the position of a layer is at the layer's center. If you'd like to move the layer relative to another reference point, you can set the layer's anchorPoint property to something like (0.0, 0.0) for its upper-left corner (on the iPhone) or (0.0, 1.0) for its lower left.

Also, this won't change the frame of the UIImageView when it's done, so if you refer to that frame later on, you may need to either take that into account or add a delegate method callback for the end of your animation to set it to the proper value.

You can also make your image move along curves, instead of straight lines, by replacing the calls to CGPathAddLineToPoint() with CGPathAddCurveToPoint().

EDIT (5/14/2009): I added the missing pathAnimation.path = pointPath line and changed a mistyped reference to curvedPath to pointPath.

like image 149
Brad Larson Avatar answered Jan 11 '23 20:01

Brad Larson