繁体   English   中英

UIImageView动画从左到右

[英]UIImageView animation from left to right

我想将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 我面临的问题是我无法完全从左向右移动它。 上面的代码只是将其从右移到中心。 我想从中心往左走。 有人可以指导我吗?

我认为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];

该代码段使视图从左到右非常接近您的描述,尽管要获得确切的效果,您可能需要稍作更改。

假设您可以定位到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
   ];

除了设置中心,您还应该研究设置转换。 使用center可以设置中心,这意味着您必须根据图像尺寸正确计算中心。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM