具有持续时间和自动反转的iOS动画

时间:2013-12-06 12:08:53

标签: ios objective-c animation uiview uiimageview

我使用UIView块API为UIImageView制作动画。我的动画连续淡出UIImageView In和Out。如何在特定的持续时间内为此设置动画?

我已经提出了这段代码

float tempDuration = 5.0;
[UIView animateWithDuration:tempDuration
                          delay:0
                        options:UIViewAnimationOptionAutoreverse | UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                         _imageView.alpha = 1;
                     }
                     completion:nil];

3 个答案:

答案 0 :(得分:7)

首先,请允许我介绍一篇 awesome 的文章,以了解动画的某些功能:

Controlling Animation Timming

在本文中,您有一个显示所需内容的部分。

你想要这样的东西:

enter image description here

因此您可以通过以下方式进行配置:

-(void) animateImageView:(UIImageView*) imageView 
            withDuration:(int) duration 
         withRepeatCount: (int) repeatCount {

     CABasicAnimation *opacityAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
     opacityAnim.fromValue = @1.0;
     opacityAnim.toValue = @0.0;
     opacityAnim.autoreverses = YES;
     opacityAnim.duration = duration/2.0/repeatCount;
     opacityAnim.removedOnCompletion = YES;
     opacityAnim.repeatCount = repeatCount;
     [imageView.layer addAnimation:opacityAnim forKey:nil];
 }

通过这种方式,您可以保证动画始终为5秒,并且可以调整重复次数。

答案 1 :(得分:3)

如果CABasicAnimation

,也许您可​​以尝试使用[UIView animateWithDiration: ... ]

它应该是这样的:

  CABasicAnimation *opacityAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
  opacityAnim.fromValue = [NSNumber numberWithFloat:1.0];
  opacityAnim.toValue = [NSNumber numberWithFloat:0.0];
  opacityAnim.autoreverses = YES;
  opacityAnim.duration = duration;
  opacityAnim.removedOnCompletion = YES;
  opacityAnim.repeatCount = 5;
  [imageView.layer addAnimation:opacityAnim forKey:nil];

答案 2 :(得分:0)

您可以执行以下更改来完成工作。

- (void)animateImageView{
    static int animcount = 1;
    float tempDuration = 1.0;
    [UIView animateWithDuration:tempDuration
                          delay:0
                        options: UIViewAnimationOptionAutoreverse
                     animations:^{
                         self.imgView.alpha = 1;
                     }
                     completion:^(BOOL finished) {
                         if(finished && animcount<5){
                             animcount+=1;
                             [self animateImageView];
                         }
                         else if (finished && animcount==5){
                             [self.imgView.layer removeAllAnimations];
                         }

                     }];
}