一种酷炫的转场卡通片

一种酷炫的转场动画

几天前,在简书上看到一个用Swift写的转场动画,觉得甚是酷炫,类似于什么值得买里面的。

于是,今天用OC写了一遍。

【效果如下】:

一种酷炫的转场卡通片


【主要实现过程】

在两个控制切换的过程中,主要要做以下几个步骤:

1、获取动画的源控制器和目标控制器

2、创建一个Cell中imageView的截图,并把imageView隐藏,这样使用户以为移动的就是imageView的假象,这点是实现的关键

3、设置目标控制器的位置,并把透明度设为0,在后面的动画中慢慢显示出来变为1

4、将截图和目标控制器的View都添加到container中,注意顺序不能错

5、执行动画


- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
    //1、获取动画的源控制器和目标控制器
    ViewController *fromVC = (ViewController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    ZMPDetailViewController *toVC = (ZMPDetailViewController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    UIView *container = [transitionContext containerView];
    
    //2、创建一个Cell中imageView的截图,并把imageView隐藏,造成使用户以为移动的就是 imageView 的假象
    UIView *snapshotView = [fromVC.selectedCell.imageView snapshotViewAfterScreenUpdates:false];
    snapshotView.frame = [container convertRect:fromVC.selectedCell.imageView.frame fromView:fromVC.selectedCell];
    fromVC.selectedCell.imageView.hidden = YES;
    
    //3.设置目标控制器的位置,并把透明度设为0,在后面的动画中慢慢显示出来变为1
    toVC.view.frame = [transitionContext finalFrameForViewController:toVC];
    toVC.view.alpha = 0;
    toVC.avatarImageView.hidden = YES;
    
    //4.都添加到 container 中。注意顺序不能错了
    [container addSubview:toVC.view];
    [container addSubview:snapshotView];
    
    //5.执行动画
    /*
     这时avatarImageView.frame的值只是跟在IB中一样的,
     如果换成屏幕尺寸不同的模拟器运行时avatarImageView会先移动到IB中的frame,动画结束后才会突然变成正确的frame。
     所以需要在动画执行前执行一次toVC.avatarImageView.layoutIfNeeded() update一次frame
     */
    [toVC.avatarImageView layoutIfNeeded];
    
    [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0 options:UIViewAnimationOptionCurveEaseInOut  animations:^{
        snapshotView.frame = toVC.avatarImageView.frame;
        toVC.view.alpha = 1;
    } completion:^(BOOL finished) {
        toVC.avatarImageView.hidden = NO;
        fromVC.selectedCell.imageView.hidden = NO;
        toVC.avatarImageView.image = toVC.image;
        [snapshotView removeFromSuperview];
        
        [transitionContext completeTransition:YES];
    }];

    
}

回退的动画跟进入的过程是类似的,就不再赘述。

源码下载:ZMPMagicMove

另外,可关注iOS开发者微信公众平台,提供更多源码资料

一种酷炫的转场卡通片


版权声明:本文为博主原创文章,未经博主允许不得转载。