2011-06-19 138 views
1

我想将我的UIImageView从左到右移动,反之亦然。我做到一半是通过使用下面的代码: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。我面临的问题是我无法完全从左向右移动它。上面的代码只是将它从右移到中心。我想从中心进一步离开。有人可以指导我吗?

回答

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

的这段代码振荡视图从左到右相当接近你的描述,虽然得到你想要的,你可能要改变了一点确切的疗效。

+0

这只是一个例子来实现,我并没有把100 X位置居然和好这个答案是没有帮助的,因为我要搬家了它左和右。你只是解释了我已经完成的一个方面的动作:( – Wasim

+0

@Wasim你的问题没有提到,根本没有动画,所以我误解了你的要求,更新了我的答案 –

+0

@Deepak谢谢你的回复:)但你仍然误解了我的问题:)我说,我完成了一半的动画,这意味着我能够从中心向右或向左动画我的UIViewImage。但我的主要动机是从屏幕中心开始动画并将其首先移动到最左侧然后最右侧。我希望我的问题现在对你更加清楚:)对不起再次打扰你再次:) – Wasim

0

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

要将其左移,请将转换设置为-320的平移。将它移回标识变换。

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