iOS自定义转场动画

来源:互联网 发布:高仿爱奇艺影视源码 编辑:程序博客网 时间:2024/05/02 01:52

http://www.jianshu.com/p/45434f73019e

更新,更简单的自定义转场集成!

几句代码快速集成自定义转场效果+ 全手势驱动

写在前面

这两天闲下来好好的研究了一下自定义转场,关于这方面的文章网络上已经很多了,作为新手,我想通过这篇文章把自己这几天的相关学习心得记录一下,方便加深印响和以后的回顾,这是我第一写技术文章,不好之处请谅解,通过这几天的学习,我尝试实现了四个效果,废话不多说,先上效果图:

DEMO ONE:一个弹性的present动画,支持手势present和dismiss


弹性pop

DEMO TWO:一个类似于KeyNote的神奇移动效果push动画,支持手势pop


神奇移动

DEMO THREE:一个翻页push效果,支持手势PUSH和POP


翻页效果

DEMO FOUR:一个小圆点扩散present效果,支持手势dimiss


扩散效果

动手前

大家都知道从iOS7开始,苹果就提供了自定义转场的API,模态推送present和dismiss、导航控制器push和pop、标签控制器的控制器切换都可以自定义转场了,关于过多的理论我就不太多说明了,大家可以先参照onevcat大神的这篇博客:WWDC 2013 Session笔记 - iOS7中的ViewController切换,我想把整个自定义转场的步骤做个总结:

  1. 我们需要自定义一个遵循的<UIViewControllerAnimatedTransitioning>协议的动画过渡管理对象,并实现两个必须实现的方法:

     //返回动画事件   - (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext; //所有的过渡动画事务都在这个方法里面完成 - (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext;
  2. 我们还需要自定义一个继承于UIPercentDrivenInteractiveTransition的手势过渡管理对象,我把它成为百分比手势过渡管理对象,因为动画的过程是通过百分比控制的
  3. 成为相应的代理,实现相应的代理方法,返回我们前两步自定义的对象就OK了 !

    模态推送需要实现如下4个代理方法,iOS8新的那个方法我暂时还没有发现它的用处,所以暂不讨论

     //返回一个管理prenent动画过渡的对象 - (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source; //返回一个管理pop动画过渡的对象 - (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed; //返回一个管理prenent手势过渡的对象 - (nullable id <UIViewControllerInteractiveTransitioning>)interactionControllerForPresentation:(id <UIViewControllerAnimatedTransitioning>)animator; //返回一个管理pop动画过渡的对象 - (nullable id <UIViewControllerInteractiveTransitioning>)interactionControllerForDismissal:(id <UIViewControllerAnimatedTransitioning>)animator;

    导航控制器实现如下2个代理方法

     //返回转场动画过渡管理对象 - (nullable id <UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController                   interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>) animationController NS_AVAILABLE_IOS(7_0); //返回手势过渡管理对象 - (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController                            animationControllerForOperation:(UINavigationControllerOperation)operation                                         fromViewController:(UIViewController *)fromVC                                           toViewController:(UIViewController *)toVC  NS_AVAILABLE_IOS(7_0);

    标签控制器也有相应的两个方法

     //返回转场动画过渡管理对象 - (nullable id <UIViewControllerInteractiveTransitioning>)tabBarController:(UITabBarController *)tabBarController               interactionControllerForAnimationController: (id <UIViewControllerAnimatedTransitioning>)animationController NS_AVAILABLE_IOS(7_0); //返回手势过渡管理对象 - (nullable id <UIViewControllerAnimatedTransitioning>)tabBarController:(UITabBarController *)tabBarController     animationControllerForTransitionFromViewController:(UIViewController *)fromVC                                       toViewController:(UIViewController *)toVC  NS_AVAILABLE_IOS(7_0);
  4. 如果看着这些常常的代理方法名头疼的话,没关系,先在demo中用起来吧,慢慢就习惯了,其实哪种自定义转场都只需要这3个步骤,如果不需要手势控制,步骤2还可以取消,现在就让我们动手来实现效果吧

动手吧!

demo one

1、我们首先创建2个控制器,为了方便我称做present操作的为vc1、被present的为vc2,点击一个控制器上的按钮可以push出另一个控制器
2、 然后我们创建一个过渡动画管理的类,遵循<UIViewControllerAnimatedTransitioning>协议,我这里是XWPresentOneTransition,由于我们要同时管理present和dismiss2个动画,你可以实现相应的两个类分别管理两个动画,但是我觉得用一个类来管理就好了,看着比较舒服,逻辑也比较紧密,因为present和dismiss的动画逻辑很类似,写在一起,可以相互参考,所以我定义了一个枚举和两个初始化方法:

    XWPresentOneTransition.h    typedef NS_ENUM(NSUInteger, XWPresentOneTransitionType) {        XWPresentOneTransitionTypePresent = 0,//管理present动画        XWPresentOneTransitionTypeDismiss//管理dismiss动画    };    @interface XWPresentOneTransition : NSObject<UIViewControllerAnimatedTransitioning>    //根据定义的枚举初始化的两个方法    + (instancetype)transitionWithTransitionType:(XWPresentOneTransitionType)type;    - (instancetype)initWithTransitionType:(XWPresentOneTransitionType)type;

3、 然后再.m文件里面实现必须实现的两个代理方法

    @implementation XWPresentOneTransition    - (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext{        return 0.5;    }    - (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{        //为了将两种动画的逻辑分开,变得更加清晰,我们分开书写逻辑,        switch (_type) {            case XWPresentOneTransitionTypePresent:                [self presentAnimation:transitionContext];                break;            case XWPresentOneTransitionTypeDismiss:                [self dismissAnimation:transitionContext];                break;        }    }    //实现present动画逻辑代码    - (void)presentAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{    }    //实现dismiss动画逻辑代码    - (void)dismissAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{    }

4、 设置vc2的transitioningDelegate,我就设为它自己咯,我实在vc2的init方法中设置的,并实现代理方法

    - (instancetype)init    {        self = [super init];        if (self) {            self.transitioningDelegate = self;            //为什么要设置为Custom,在最后说明.            self.modalPresentationStyle = UIModalPresentationCustom;        }        return self;    }    - (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{        //这里我们初始化presentType        return [XWPresentOneTransition transitionWithTransitionType:XWPresentOneTransitionTypePresent];    }    - (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{        //这里我们初始化dismissType        return [XWPresentOneTransition transitionWithTransitionType:XWPresentOneTransitionTypeDismiss];    }

5、 至此我们所有的准备工作就做好了,下面只需要专心在presentAnimation:方法和dismissAnimation方法中实现动画逻辑就OK了,先看presentAnimation:

        - (void)presentAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{`        //通过viewControllerForKey取出转场前后的两个控制器,这里toVC就是vc1、fromVC就是vc2        UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];        UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];        //snapshotViewAfterScreenUpdates可以对某个视图截图,我们采用对这个截图做动画代替直接对vc1做动画,因为在手势过渡中直接使用vc1动画会和手势有冲突,    如果不需要实现手势的话,就可以不是用截图视图了,大家可以自行尝试一下        UIView *tempView = [fromVC.view snapshotViewAfterScreenUpdates:NO];        tempView.frame = fromVC.view.frame;        //因为对截图做动画,vc1就可以隐藏了        fromVC.view.hidden = YES;        //这里有个重要的概念containerView,如果要对视图做转场动画,视图就必须要加入containerView中才能进行,可以理解containerView管理着所有做转场动画的视图        UIView *containerView = [transitionContext containerView];        //将截图视图和vc2的view都加入ContainerView中        [containerView addSubview:tempView];        [containerView addSubview:toVC.view];        //设置vc2的frame,因为这里vc2present出来不是全屏,且初始的时候在底部,如果不设置frame的话默认就是整个屏幕咯,这里containerView的frame就是整个屏幕        toVC.view.frame = CGRectMake(0, containerView.height, containerView.width, 400);        //开始动画吧,使用产生弹簧效果的动画API        [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0 usingSpringWithDamping:0.55 initialSpringVelocity:1.0 / 0.55 options:0 animations:^{            //首先我们让vc2向上移动            toVC.view.transform = CGAffineTransformMakeTranslation(0, -400);            //然后让截图视图缩小一点即可            tempView.transform = CGAffineTransformMakeScale(0.85, 0.85);        } completion:^(BOOL finished) {            //使用如下代码标记整个转场过程是否正常完成[transitionContext transitionWasCancelled]代表手势是否取消了,如果取消了就传NO表示转场失败,反之亦然,如果不用手势present的话直接传YES也是可以的,但是无论如何我们都必须标记转场的状态,系统才知道处理转场后的操作,否者认为你一直还在转场中,会出现无法交互的情况,切记!            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];            //转场失败后的处理            if ([transitionContext transitionWasCancelled]) {                //失败后,我们要把vc1显示出来                fromVC.view.hidden = NO;                //然后移除截图视图,因为下次触发present会重新截图                [tempView removeFromSuperview];            }            }];        }

再看dismissAnimation 方法

        - (void)dismissAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{        //注意在dismiss的时候fromVC就是vc2了,toVC才是VC1了,注意这个关系        UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];        UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];        //参照present动画的逻辑,present成功后,containerView的最后一个子视图就是截图视图,我们将其取出准备动画        UIView *tempView = [transitionContext containerView].subviews[0];        //动画吧        [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{            //因为present的时候都是使用的transform,这里的动画只需要将transform恢复就可以了            fromVC.view.transform = CGAffineTransformIdentity;            tempView.transform = CGAffineTransformIdentity;        } completion:^(BOOL finished) {            if ([transitionContext transitionWasCancelled]) {                //失败了标记失败                [transitionContext completeTransition:NO];            }else{                //如果成功了,我们需要标记成功,同时让vc1显示出来,然后移除截图视图,                [transitionContext completeTransition:YES];                toVC.view.hidden = NO;                [tempView removeFromSuperview];            }            }];        }

6、如果不需要手势控制,这个转场就算完成了,下面我们来添加手势,首先创建一个手势过渡管理的类,我这里是XWInteractiveTransition,因为无论哪一种转场,手势控制的实质都是一样的,我干脆就把这个手势过渡管理的类封装了一下,具体可以在.h文件里面查看,在接下来的三个转场效果中我们都可以便捷的是使用它 .m文件说明

        //通过这个方法给控制器的View添加相应的手势        - (void)addPanGestureForViewController:(UIViewController *)viewController{        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];        //将传入的控制器保存,因为要利用它触发转场操作        self.vc = viewController;        [viewController.view addGestureRecognizer:pan];            }          //关键的手势过渡的过程        - (void)handleGesture:(UIPanGestureRecognizer *)panGesture{        //persent是根据panGesture的移动距离获取的,这里就不说明了,可具体去代码中查看        switch (panGesture.state) {        case UIGestureRecognizerStateBegan:            //手势开始的时候标记手势状态,并开始相应的事件,它的作用在使用这个类的时候说明            self.interation = YES;            //手势开始是触发对应的转场操作,方法代码在后面            [self startGesture];            break;        case UIGestureRecognizerStateChanged:{            //手势过程中,通过updateInteractiveTransition设置转场过程进行的百分比,然后系统会根据百分比自动布局控件,不用我们控制了            [self updateInteractiveTransition:persent];            break;        }        case UIGestureRecognizerStateEnded:{            //手势完成后结束标记并且判断移动距离是否过半,过则finishInteractiveTransition完成转场操作,否者取消转场操作,转场失败            self.interation = NO;            if (persent > 0.5) {                [self finishInteractiveTransition];            }else{                [self cancelInteractiveTransition];            }            break;        }        default:            break;            }        }          //触发对应转场操作的代码如下,根据type(type是我自定义的枚举值)我们去判断是触发哪种操作,对于push和present由于要传入需要push和present的控制器,为了解耦,我用block把这个操作交个控制器去做了,让这个手势过渡管理者可以充分被复用        - (void)startGesture{        switch (_type) {        case XWInteractiveTransitionTypePresent:{            if (_presentConifg) {                _presentConifg();            }        }            break;        case XWInteractiveTransitionTypeDismiss:            [_vc dismissViewControllerAnimated:YES completion:nil];            break;        case XWInteractiveTransitionTypePush:{            if (_pushConifg) {                _pushConifg();            }        }            break;        case XWInteractiveTransitionTypePop:            [_vc.navigationController popViewControllerAnimated:YES];            break;            }        }

7、 手势过渡管理者就算完毕了,这个手势管理者可以用到其他任何的模态和导航控制器转场中,以后都不用在写了,现在把他用起来,在vc2和vc1中创建相应的手势过渡管理者,并放到相应的代理方法去返回它

        //创建dismiss手势过渡管理者,present的手势过渡要在vc1中创建,因为present的手势是加载vc1的view上的,我选择通过代理吧vc1中创建的手势过渡管理者传过来        self.interactiveDismiss = [XWInteractiveTransition interactiveTransitionWithTransitionType:XWInteractiveTransitionTypeDismiss             GestureDirection:XWInteractiveTransitionGestureDirectionDown];            [self.interactiveDismiss addPanGestureForViewController:self];            [_interactivePush addPanGestureForViewController:self.navigationController];            //返回dissmiss的手势过渡管理        - (id<UIViewControllerInteractiveTransitioning>)interactionControllerForDismissal:        (id<UIViewControllerAnimatedTransitioning>)animator{            //在没有用手势触发的dismiss的时候需要传nil,否者无法点击dimiss,所以interation就是用来判断是否是手势触发转场的            return _interactiveDismiss.interation ? _interactiveDismiss : nil;        }        //返回present的手势管理,这个手势管理者是在vc1中创建的,我用代理传过来的        - (id<UIViewControllerInteractiveTransitioning>)interactionControllerForPresentation:        (id<UIViewControllerAnimatedTransitioning>)animator{            XWInteractiveTransition *interactivePresent = [_delegate interactiveTransitionForPresent];            return interactivePresent.interation ? interactivePresent : nil;        }

8、 终于完成了,再来看一下效果,是不是还不错!


弹性pop

DEMO TWO

1、 创建动画过渡管理者的代码就不重复说明了,我仿造demo1,利用枚举创建了一个同时管理push和pop的管理者,然后动画的逻辑代码集中在doPushAnimationdoPopAnimation中,很多内容都在demo1中说明了,下面的注释就比较简单了,来看看

        //Push动画逻辑        - (void)doPushAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{        XWMagicMoveController *fromVC = (XWMagicMoveController *)[transitionContext     viewControllerForKey:UITransitionContextFromViewControllerKey];        XWMagicMovePushController *toVC = (XWMagicMovePushController *)[transitionContext     viewControllerForKey:UITransitionContextToViewControllerKey];        //拿到当前点击的cell的imageView        XWMagicMoveCell *cell = (XWMagicMoveCell *)[fromVC.collectionView cellForItemAtIndexPath:fromVC.currentIndexPath];        UIView *containerView = [transitionContext containerView];        //snapshotViewAfterScreenUpdates 对cell的imageView截图保存成另一个视图用于过渡,并将视图转换到当前控制器的坐标        UIView *tempView = [cell.imageView snapshotViewAfterScreenUpdates:NO];        tempView.frame = [cell.imageView convertRect:cell.imageView.bounds toView: containerView];        //设置动画前的各个控件的状态        cell.imageView.hidden = YES;        toVC.view.alpha = 0;        toVC.imageView.hidden = YES;        //tempView 添加到containerView中,要保证在最前方,所以后添加        [containerView addSubview:toVC.view];        [containerView addSubview:tempView];        //开始做动画        [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0.0 usingSpringWithDamping:0.55     initialSpringVelocity:1 / 0.55 options:0 animations:^{            tempView.frame = [toVC.imageView convertRect:toVC.imageView.bounds toView:containerView];            toVC.view.alpha = 1;        } completion:^(BOOL finished) {            //tempView先隐藏不销毁,pop的时候还会用            tempView.hidden = YES;            toVC.imageView.hidden = NO;            //如果动画过渡取消了就标记不完成,否则才完成,这里可以直接写YES,如果有手势过渡才需要判断,必须标记,否则系统不会中动画完成的部署,会出现无法交互之类的bug            [transitionContext completeTransition:YES];            }];        }      //Pop动画逻辑        - (void)doPopAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{        XWMagicMovePushController *fromVC = (XWMagicMovePushController *)[transitionContext     viewControllerForKey:UITransitionContextFromViewControllerKey];        XWMagicMoveController *toVC = (XWMagicMoveController *)[transitionContext     viewControllerForKey:UITransitionContextToViewControllerKey];        XWMagicMoveCell *cell = (XWMagicMoveCell *)[toVC.collectionView cellForItemAtIndexPath:toVC.currentIndexPath];        UIView *containerView = [transitionContext containerView];        //这里的lastView就是push时候初始化的那个tempView        UIView *tempView = containerView.subviews.lastObject;        //设置初始状态        cell.imageView.hidden = YES;        fromVC.imageView.hidden = YES;        tempView.hidden = NO;        [containerView insertSubview:toVC.view atIndex:0];        [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0.0 usingSpringWithDamping:0.55     initialSpringVelocity:1 / 0.55 options:0 animations:^{            tempView.frame = [cell.imageView convertRect:cell.imageView.bounds toView:containerView];            fromVC.view.alpha = 0;        } completion:^(BOOL finished) {            //由于加入了手势必须判断            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];            if ([transitionContext transitionWasCancelled]) {//手势取消了,原来隐藏的imageView要显示出来                //失败了隐藏tempView,显示fromVC.imageView                tempView.hidden = YES;                fromVC.imageView.hidden = NO;            }else{//手势成功,cell的imageView也要显示出来                //成功了移除tempView,下一次pop的时候又要创建,然后显示cell的imageView                cell.imageView.hidden = NO;                [tempView removeFromSuperview];            }          }];        }

2、 然后将这个动画过渡管理者和demo1中创建的手势过渡管理者分别放到正确的代理方法中,用起来就可以了


神奇移动

DEMO THREE

1、 直接看看doPushAnimationdoPopAnimation的动画逻辑,这次使用了CAGradientLayer给动画的过程增加了阴影

    //Push动画逻辑    - (void)doPushAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];    //还是使用截图大法来完成动画,不然还是会有奇妙的bug;    UIView *tempView = [fromVC.view snapshotViewAfterScreenUpdates:NO];    tempView.frame = fromVC.view.frame;    UIView *containerView = [transitionContext containerView];    //将将要动画的视图加入containerView    [containerView addSubview:toVC.view];    [containerView addSubview:tempView];    fromVC.view.hidden = YES;    [containerView insertSubview:toVC.view atIndex:0];    //设置AnchorPoint,并增加3D透视效果    [tempView setAnchorPointTo:CGPointMake(0, 0.5)];    CATransform3D transfrom3d = CATransform3DIdentity;    transfrom3d.m34 = -0.002;    containerView.layer.sublayerTransform = transfrom3d;    //增加阴影    CAGradientLayer *fromGradient = [CAGradientLayer layer];    fromGradient.frame = fromVC.view.bounds;    fromGradient.colors = @[(id)[UIColor blackColor].CGColor,                        (id)[UIColor blackColor].CGColor];    fromGradient.startPoint = CGPointMake(0.0, 0.5);    fromGradient.endPoint = CGPointMake(0.8, 0.5);    UIView *fromShadow = [[UIView alloc]initWithFrame:fromVC.view.bounds];    fromShadow.backgroundColor = [UIColor clearColor];    [fromShadow.layer insertSublayer:fromGradient atIndex:1];    fromShadow.alpha = 0.0;    [tempView addSubview:fromShadow];    CAGradientLayer *toGradient = [CAGradientLayer layer];    toGradient.frame = fromVC.view.bounds;    toGradient.colors = @[(id)[UIColor blackColor].CGColor,                            (id)[UIColor blackColor].CGColor];    toGradient.startPoint = CGPointMake(0.0, 0.5);    toGradient.endPoint = CGPointMake(0.8, 0.5);    UIView *toShadow = [[UIView alloc]initWithFrame:fromVC.view.bounds];    toShadow.backgroundColor = [UIColor clearColor];    [toShadow.layer insertSublayer:toGradient atIndex:1];    toShadow.alpha = 1.0;    [toVC.view addSubview:toShadow];    //动画吧    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{        //翻转截图视图        tempView.layer.transform = CATransform3DMakeRotation(-M_PI_2, 0, 1, 0);        //给阴影效果动画        fromShadow.alpha = 1.0;        toShadow.alpha = 0.0;    } completion:^(BOOL finished) {        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];        if ([transitionContext transitionWasCancelled]) {            //失败后记得移除截图,下次push又会创建            [tempView removeFromSuperview];            fromVC.view.hidden = NO;        }    }];}}    //Pop动画逻辑    - (void)doPopAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];    UIView *containerView = [transitionContext containerView];    //拿到push时候的的截图视图    UIView *tempView = containerView.subviews.lastObject;    [containerView addSubview:toVC.view];    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{           //把截图视图翻转回来        tempView.layer.transform = CATransform3DIdentity;        fromVC.view.subviews.lastObject.alpha = 1.0;        tempView.subviews.lastObject.alpha = 0.0;    } completion:^(BOOL finished) {        if ([transitionContext transitionWasCancelled]) {            [transitionContext completeTransition:NO];        }else{            [transitionContext completeTransition:YES];            [tempView removeFromSuperview];            toVC.view.hidden = NO;        }    }];}

2、 最后用上去在加上手势就是这个样子啦


翻页效果

DEMO FOUR

1、 直接看看doPresentAnimationdoDismissAnimation的动画逻辑,这次使用了CASharpLayer和UIBezierPath

    //Present动画逻辑    - (void)presentAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];    //拿到控制器获取button的frame来设置动画的开始结束的路径    UINavigationController *fromVC = (UINavigationController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];    XWCircleSpreadController *temp = fromVC.viewControllers.lastObject;    UIView *containerView = [transitionContext containerView];    [containerView addSubview:toVC.view];    //画两个圆路径    UIBezierPath *startCycle =  [UIBezierPath bezierPathWithOvalInRect:temp.buttonFrame];    //通过如下方法计算获取在x和y方向按钮距离边缘的最大值,然后利用勾股定理即可算出最大半径    CGFloat x = MAX(temp.buttonFrame.origin.x, containerView.frame.size.width - temp.buttonFrame.origin.x);    CGFloat y = MAX(temp.buttonFrame.origin.y, containerView.frame.size.height - temp.buttonFrame.origin.y);    //勾股定理计算半径    CGFloat radius = sqrtf(pow(x, 2) + pow(y, 2));    //以按钮中心为圆心,按钮中心到屏幕边缘的最大距离为半径,得到转场后的path    UIBezierPath *endCycle = [UIBezierPath bezierPathWithArcCenter:containerView.center radius:radius startAngle:0 endAngle:M_PI * 2 clockwise:YES];    //创建CAShapeLayer进行遮盖    CAShapeLayer *maskLayer = [CAShapeLayer layer];    //设置layer的path保证动画后layer不会回弹    maskLayer.path = endCycle.CGPath;    //将maskLayer作为toVC.View的遮盖    toVC.view.layer.mask = maskLayer;    //创建路径动画    CABasicAnimation *maskLayerAnimation = [CABasicAnimation animationWithKeyPath:@"path"];    maskLayerAnimation.delegate = self;    //动画是加到layer上的,所以必须为CGPath,再将CGPath桥接为OC对象    maskLayerAnimation.fromValue = (__bridge id)(startCycle.CGPath);    maskLayerAnimation.toValue = (__bridge id)((endCycle.CGPath));    maskLayerAnimation.duration = [self transitionDuration:transitionContext];    maskLayerAnimation.delegate = self;    //设置淡入淡出    maskLayerAnimation.timingFunction = [CAMediaTimingFunction  functionWithName:kCAMediaTimingFunctionEaseInEaseOut];    [maskLayerAnimation setValue:transitionContext forKey:@"transitionContext"];    [maskLayer addAnimation:maskLayerAnimation forKey:@"path"];}    //Dismiss动画逻辑    - (void)dismissAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];    UINavigationController *toVC = (UINavigationController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];    XWCircleSpreadController *temp = toVC.viewControllers.lastObject;    UIView *containerView = [transitionContext containerView];    //画两个圆路径    CGFloat radius = sqrtf(containerView.frame.size.height * containerView.frame.size.height + containerView.frame.size.width * containerView.frame.size.width) / 2;    UIBezierPath *startCycle = [UIBezierPath bezierPathWithArcCenter:containerView.center radius:radius startAngle:0 endAngle:M_PI * 2 clockwise:YES];    UIBezierPath *endCycle =  [UIBezierPath bezierPathWithOvalInRect:temp.buttonFrame];    //创建CAShapeLayer进行遮盖    CAShapeLayer *maskLayer = [CAShapeLayer layer];    maskLayer.fillColor = [UIColor greenColor].CGColor;    maskLayer.path = endCycle.CGPath;    fromVC.view.layer.mask = maskLayer;    //创建路径动画    CABasicAnimation *maskLayerAnimation = [CABasicAnimation animationWithKeyPath:@"path"];    maskLayerAnimation.delegate = self;    maskLayerAnimation.fromValue = (__bridge id)(startCycle.CGPath);    maskLayerAnimation.toValue = (__bridge id)((endCycle.CGPath));    maskLayerAnimation.duration = [self transitionDuration:transitionContext];    maskLayerAnimation.delegate = self;    maskLayerAnimation.timingFunction = [CAMediaTimingFunction  functionWithName:kCAMediaTimingFunctionEaseInEaseOut];    [maskLayerAnimation setValue:transitionContext forKey:@"transitionContext"];    [maskLayer addAnimation:maskLayerAnimation forKey:@"path"];}

2、最后在animationDidStop的代理方法中处理到动画的完成逻辑,处理方式都类似

    - (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{    switch (_type) {        case XWCircleSpreadTransitionTypePresent:{            id<UIViewControllerContextTransitioning> transitionContext = [anim valueForKey:@"transitionContext"];            [transitionContext completeTransition:YES];            [transitionContext viewControllerForKey:UITransitionContextToViewKey].view.layer.mask = nil;        }            break;        case XWCircleSpreadTransitionTypeDismiss:{            id<UIViewControllerContextTransitioning> transitionContext = [anim valueForKey:@"transitionContext"];            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];            if ([transitionContext transitionWasCancelled]) {                [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey].view.layer.mask = nil;            }        }            break;    }}

3、 最后用上去在加上手势就是这个样子啦


扩散效果

总结

1、关于:self.modalPresentationStyle = UIModalPresentationCustom;我查看了视图层级后发现,如果使用了Custom,在present动画完成的时候,presentingView也就是demo one中的vc1的view会从containerView中移除,只是移除,并未销毁,此时还被持有着(dismiss后还得回来呢!),如果设置custom,那么present完成后,它一直都在containerView中,只是在最后面,所以需不需要设置custom可以看动画完成后的情况,是否还需要看见presentingViewController,但是记住如果没有设置custom,在disMiss的动画逻辑中,要把它加回containerView中,不然就不在咯~!
2、感觉写了好多东西,其实只要弄懂了转场的逻辑,其实就只需要写动画的逻辑就行了,其他东西都是固定的,而且苹果提供的这种控制转场的方式可充分解耦,除了写的手势过渡管理可以拿到任何地方使用,所有的动画过渡管理者都可以很轻松的复用到其他转场中,都不用分是何种转场,demo没有写标签控制器的转场,实现方法也是完全类似的,大家可以尝试一下,四个demo的github地址:自定义转场动画demo



文/wazrx(简书作者)
原文链接:http://www.jianshu.com/p/45434f73019e
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

0 0
原创粉丝点击