Prerna chavan
Prerna chavan

Reputation: 3249

Adding new animation to the existing one

I my application i want to move UIImageView from the default position to the point where user has tapped. But if before completing this animation user again taps on other point, that imageView should not start from the original position instead it should start from the point where it had stopped the animation after tapping the new point. How can i do this. Following is my code to move the imageView to the position of the user tap.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{


UITouch *touch=[[event allTouches]anyObject];
touchedPoint= [touch locationInView:touch.view];

[imageViews.layer removeAllAnimations];

[UIImageView animateWithDuration:2.0 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
    [CATransaction begin];        
    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    pathAnimation.duration = 2.0f;
    pathAnimation.calculationMode = kCAAnimationPaced;
    animationPath = [UIBezierPath bezierPath];
    [animationPath moveToPoint:imageViews.center];
    [animationPath addLineToPoint:CGPointMake(touchedPoint.x,touchedPoint.y)];

    pathAnimation.path = animationPath.CGPath;
    pathAnimation.fillMode = kCAFillModeForwards;
    pathAnimation.removedOnCompletion = NO;
    [imageViews.layer addAnimation:pathAnimation forKey:@"animatePosition"];
    [CATransaction commit];


}
completion:nil]; //or completion:^(BOOL) finished { your code here for when the animation ended}];

}

Upvotes: 2

Views: 250

Answers (2)

John Smith
John Smith

Reputation: 2032

  1. define a global CGPoint;
  2. start a 0.1 seconds step repeating timer along the animation (at user's first tap).
  3. at each tick count, read your image's location and set the CGPoint defined above.
  4. after the animation starts, when the user taps again, you stop the previous animation, and initiate another one, using the above CGPoint as "moveToPoint".

Invalidate the timer if the animation stops before the user taps to change it's direction.

Upvotes: 0

George
George

Reputation: 4029

Use this instead :

[UIImageView animateWithDuration:2.0 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
} completion:nil];

That UIViewAnimationOptionBeginFromCurrentState option will make the animation start from the current position of the image. So if you are moving the image with another animation it will all blend in nicely.

Hope this helps.

Cheers!

Upvotes: 1

Related Questions