UIImageView动画从左到右

时间:2011-06-19 12:57:44

标签: objective-c ios cocoa-touch uiimageview core-animation

我想将我的UIImageView从左向右移动,反之亦然。我使用以下代码完成了一半:

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

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

[UIView commitAnimations];

moverUIImageView的位置。我面临的问题是我无法完全从左向右移动它。上面的代码只是从右到中移动它。我想从中心向左走。有人可以指导我吗?

3 个答案:

答案 0 :(得分:6)

我认为UIKit动画不会为您提供直接的关键帧动画来获得振荡效果。我们可以尝试通过触发一个又一个动画来使用委托来实现它,但它不如CAKeyframeAnimation那么高效。要使用此功能,您必须在项目和QuartzCore中包含#import <QuartzCore/QuartzCore.h>框架。你可以通过做这样的事情来实现你的振荡效果,

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

这段代码会使视图从左到右摆动,非常接近您的描述,但要获得您想要的确切效果,可能需要稍微更改一下。

答案 1 :(得分:4)

假设您可以定位iOS4,可以通过

实现
   typedef void (^completionBlock)(BOOL);
   completionBlock moveToExtremeRight = ^(BOOL finished){
       // animate, with repetition, from extreme left to extreme right 
       [UIView animateWithDuration:2.0 // twice as long!
                          delay:0.0
                         options:UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionRepeat|UIViewAnimationAutoReverse
                     animations:^{
                          mover.transform = CGAffineTransformMakeTranslation(100, 0);
                     }
                     completion:nil
       ];
   };
   mover.transform = CGAffineTransformIdentity;
   // animate once, to the extreme left
   [UIView animateWithDuration:1.0
                          delay:0.0
                        options:UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                          // or whatever is appropriate 'extreme left'
                          mover.transform = CGAffineTransformMakeTranslation(-100, 0);
                     }
                     // on completion, start a repeating animation
                     completion:moveToExtremeRight
   ];

答案 2 :(得分:0)

您应该考虑设置变换,而不是设置中心。使用中心设置中心,这意味着您必须根据图像大小正确计算中心。

要向左移动,请将变换设置为-320的平移。要将其移回,请将其设置为identitiy变换。