iPhone Developer Tips Stats: Past 30 days - Pageviews: 88,766 Visitors: 61,679 Thank you everyone! Let's shoot for 100,000 by May. Pass it on...
|
I was recently working on an application where I needed to animate an image moving on the screen. It surprisingly easy to do accomplish this effect. Let’s me show you the method that I came up with.
The moveImage method takes five parameters – the image to move, duration of the animation in seconds, the animation curve to apply, and the x / y coordinates for the final image location.
Method To Move an Image
Here is how the method looks:
- (void)moveImage:(UIImageView *)image duration:(NSTimeInterval)duration
curve:(int)curve x:(CGFloat)x y:(CGFloat)y
{
// Setup the animation
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:duration];
[UIView setAnimationCurve:curve];
[UIView setAnimationBeginsFromCurrentState:YES];
// The transform matrix
CGAffineTransform transform = CGAffineTransformMakeTranslation(x, y);
image.transform = transform;
// Commit the changes
[UIView commitAnimations];
}
Calling the Move Method
Most likely you won’t use hard-coded values as shown in the code example below, however, you get the idea on how easy it is to call the method defined above:
- (void)startApp
{
UIImageView *imageToMove =
[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Square.png"]];
imageToMove.frame = CGRectMake(10, 10, 20, 100);
[self.view addSubview:imageToMove];
// Move the image
[self moveImage:imageToMove duration:3.0
curve:UIViewAnimationCurveLinear x:50.0 y:50.0];
...
}
Comments
One Response to “Move an Image with Animation”
Leave Comment
Great Post. Just what I was Looking for.