簡體   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