Search code examples
objective-cioscocoa-touchuiimageviewcore-animation

UIImageView animation from left to right


I want to move my UIImageView from left to right and vice versa. I accomplish half of it by using the following code:

[UIView setAnimationDuration:1.0];
[UIView setAnimationRepeatCount:10];
[UIView setAnimationRepeatAutoreverses:YES];

CGPoint pos = mover.center;
pos.x = 100.0f;
mover.center = pos;

[UIView commitAnimations];

Where mover is a UIImageView. The problem I am facing is that I am unable to move it from left to right completely. The above code is only moving it from right to center. I want to go further left from center. Can anybody guide me please?


Solution

  • I don't think UIKit animations provide you direct key frame animations to get the oscillation effect. We can try to achieve it using delegates by triggering one animation after another but it is not as efficient as CAKeyframeAnimation. To use this, you will have to include the QuartzCore framework in your project and #import <QuartzCore/QuartzCore.h>. You can achieve your oscillation effect by doing something like this,

    self.mover.center = CGPointMake(160, 240);
    
    CAKeyframeAnimation *animation;
    
    animation = [CAKeyframeAnimation animationWithKeyPath:@"position.x"];
    animation.duration = 3.0f;
    animation.repeatCount = 10;
    animation.values = [NSArray arrayWithObjects:
                        [NSNumber numberWithFloat:160.0f],
                        [NSNumber numberWithFloat:320.0f],
                        [NSNumber numberWithFloat:160.0f],
                        [NSNumber numberWithFloat:0.0f],
                        [NSNumber numberWithFloat:160.0f], nil]; 
    animation.keyTimes = [NSArray arrayWithObjects:
                          [NSNumber numberWithFloat:0.0],
                          [NSNumber numberWithFloat:0.25],
                          [NSNumber numberWithFloat:.5], 
                          [NSNumber numberWithFloat:.75],
                          [NSNumber numberWithFloat:1.0], nil];    
    
    animation.removedOnCompletion = NO;
    
    [self.mover.layer addAnimation:animation forKey:nil];
    

    This snippet of code oscillates a view left to right pretty close to your description although to get the exact effect you want you might have to change it a little.