iOS 连续翻转动画

项目的任务,需要实现一个类似于下图的翻转动画,图片在翻转的同时,还要进行改变。翻转过去用时1秒,翻转回来用时1秒,展示3秒


single.gif
-(void)startTransformAnimation{
    WeakSelf(weakSelf)
    CustomBtn *btn = [_banner viewWithTag:26];
    [UIView animateWithDuration:1.0 animations:^{
        btn.topImage.layer.transform = CATransform3DMakeRotation((M_PI/2), 0,1,0);
    } completion:^(BOOL finished) {
        [weakSelf changeImgWithBtn:btn];
        [UIView animateWithDuration:1.0 animations:^{
            btn.topImage.layer.transform = CATransform3DMakeRotation(0, 0,1,0);
        } completion:^(BOOL finished) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(3.0* NSEC_PER_SEC)),dispatch_get_main_queue(),^{
                
                [weakSelf startTransformAnimation];
                
            });
        }];
    }];
}

切换图片

- (void)changeImgWithBtn:(CustomBtn *)btn
{
    if (btn.topImage.tag == 1001) {
        [btn.topImage sd_setImageWithURL:[NSURL URLWithString:((functionModel*)self.imgArr[btn.tag-20]).icon]];
        btn.topImage.tag = 1002;
    }else{
        [btn.topImage sd_setImageWithURL:[NSURL URLWithString:((functionModel*)self.imgArr[3]).icon]];
        btn.topImage.tag = 1001;
    }
  
}

后来产品提出需求:可配置执行动画的按钮,多个按钮同时执行动画


double.gif

上面的方法肯定是不行了,使用CAKeyframeAnimation来实现

/**
 * 翻转动画
 */
- (void)layerRotation {
      WeakSelf(weakSelf)
    for (int i=0; i<8; i++) {
         CustomBtn *btn = [_banner viewWithTag:20+i];
        [self addLayerRotationWithBtn:btn];
    }
    ///第一次切换图片
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(1.0* NSEC_PER_SEC)),dispatch_get_main_queue(),^{
        for (int i=0; i<8; i++) {
            CustomBtn *btn = [_banner viewWithTag:20+i];
           [weakSelf changeImgWithBtn:btn];
        }
    });
    ///循环动画
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(5.0* NSEC_PER_SEC)),dispatch_get_main_queue(),^{
        [weakSelf layerRotation];
        
    });
}

动画实现

- (void)addLayerRotationWithBtn:(CustomBtn *)Btn {
    CAKeyframeAnimation *keyAnimation = [CAKeyframeAnimation animation];
    // 旋转角度, 其中的value表示图像旋转的最终位置
    keyAnimation.values = [NSArray arrayWithObjects:
                           [NSValue valueWithCATransform3D:CATransform3DMakeRotation(0, 0,1,0)],
                           [NSValue valueWithCATransform3D:CATransform3DMakeRotation((M_PI/2), 0,1,0)],
                           [NSValue valueWithCATransform3D:CATransform3DMakeRotation(0, 0,1,0)],
                           [NSValue valueWithCATransform3D:CATransform3DMakeRotation(0, 0,1,0)],
                           nil];
    keyAnimation.keyTimes = @[@(0),@(0.2),@(0.4),@(1.0)];//每一个的取值范围是0-1
    keyAnimation.duration = 5.0 ;
    keyAnimation.repeatCount = 1;
    [Btn.topImage.layer addAnimation:keyAnimation forKey:@"transform"];
}

你可能感兴趣的:(iOS 连续翻转动画)