iOS开发CAAnimation详解

https://www.cnblogs.com/WJJ-Dream/p/5817283.html

Core Animation,即为核心动画,它是一组非常强大的动画处理API,使用它能做出非常炫丽的动画效果,而且往往是事半功倍。也就是说,使用少量的代码就可以实现非常强大的功能。Core Animation可以用在Mac OS X和iOS平台。Core Animation的动画执行过程都是在后台操作的,不会阻塞主线程。要注意的是,Core Animation是直接作用在CALayer上的,并非UIView。

1. 使用步骤

  1. 使用它需要先添加QuartzCore.framework框架和引入主头文件<QuartzCore/QuartzCore.h>(iOS7不需要);
  2. 初始化一个CAAnimation对象,并设置一些动画相关属性;
  3. 通过调用CALayer的addAnimation:forKey:方法增加CAAnimation对象到CALayer中,这样就能开始执行动画了;
  4. 通过调用CALayer的removeAnimationForKey:方法可以停止CALayer中的动画。

2. 结构

CAAnimation是所有动画对象的父类,负责控制动画的持续时间和速度,是个抽象类,不能直接使用,应该使用它具体的子类。属性:

duration:动画的持续时间

repeatCount:动画的重复次数

repeatDuration:动画的重复时间

removedOnCompletion:默认为YES,代表动画执行完毕后就从图层上移除,图形会恢复到动画执行前的状态。如果想让图层保持显示动画执行后的状态,那就设置为NO,不过还要设置fillMode为kCAFillModeForwards

fillMode:决定当前对象在非active时间段的行为。比如动画开始之前,动画结束之后

beginTime:可以用来设置动画延迟执行时间,若想延迟2s,就设置为CACurrentMediaTime()+2,CACurrentMediaTime()为图层的当前时间

timingFunction:速度控制函数,控制动画运行的节奏

delegate:动画代理

 

3. 子类

  1. CAPropertyAnimation,是CAAnimation的子类,也是个抽象类,要想创建动画对象,应该使用它的两个子类:CABasicAnimation和CAKeyframeAnimation。
    属性解析:
    1. keyPath:通过指定CALayer的一个属性名称为keyPath(NSString类型),并且对CALayer的这个属性的值进行修改,达到相应的动画效果。比如,指定@”position”为keyPath,就修改CALayer的position属性的值,以达到平移的动画效果。
  2. CABasicAnimation
    属性解析:
    1. fromValue:keyPath相应属性的初始值。
    2. toValue:keyPath相应属性的结束值。
    3. 随着动画的进行,在长度为duration的持续时间内,keyPath相应属性的值从fromValue渐渐地变为toValue。
    4. 如果fillMode=kCAFillModeForwardsremovedOnComletion=NO,那么在动画执行完毕后,图层会保持显示动画执行后的状态。但在实质上,图层的属性值还是动画执行前的初始值,并没有真正被改变。比如,CALayerposition初始值为(0,0)CABasicAnimationfromValue(10,10)toValue(100,100),虽然动画执行完毕后图层保持在(100,100)这个位置,实质上图层的position还是为(0,0)
  1. CAKeyframeAnimation,CApropertyAnimation的子类,跟CABasicAnimation的区别是:CABasicAnimation只能从一个数值(fromValue)变到另一个数值(toValue),而CAKeyframeAnimation会使用一个NSArray保存这些数值。
    属性解析:
  1. values:就是上述的NSArray对象。里面的元素称为”关键帧”(keyframe)。动画对象会在指定的时间(duration)内,依次显示values数组中的每一个关键帧。
  2. path:可以设置一个CGPathRef\CGMutablePathRef,让层跟着路径移动。path只对CALayer的anchorPoint和position起作用。如果你设置了path,那么values将被忽略。
  3. keyTimes:可以为对应的关键帧指定对应的时间点,其取值范围为0到1.0,keyTimes中的每一个时间值都对应values中的每一帧.当keyTimes没有设置的时候,各个关键帧的时间是平分的。
  4. CABasicAnimation可看做是最多只有2个关键帧的CAKeyframeAnimation。
  1. CAAnimationGroup,CAAnimation的子类,可以保存一组动画对象,将CAAnimationGroup对象加入层后,组中所有动画对象可以同时并发运行。
    属性解析:
  1. animations:用来保存一组动画对象的NSArray。
  2. 默认情况下,一组动画对象是同时运行的,也可以通过设置动画对象的beginTime属性来更改动画的开始时间。
  1. CATransition,CAAnimation的子类,用于做转场动画,能够为层提供移出屏幕和移入屏幕的动画效果。iOS比Mac OS X的转场动画效果少一点。UINavigationController就是通过CATransition实现了将控制器的视图推入屏幕的动画效果。
    属性解析:
  1. type:动画过渡类型。
  2. subtype:动画过渡方向。
  3. startProgress:动画起点(在整体动画的百分比)。
  4. endProgress:动画终点(在整体动画的百分比)。
    1. /* 过渡效果
  5.   fade     //交叉淡化过渡(不支持过渡方向) kCATransitionFade
  6.   push     //新视图把旧视图推出去  kCATransitionPush
  7.   moveIn   //新视图移到旧视图上面   kCATransitionMoveIn
      reveal   //将旧视图移开,显示下面的新视图  kCATransitionReveal
      cube     //立方体翻滚效果
      oglFlip  //上下左右翻转效果
      suckEffect   //收缩效果,如一块布被抽走(不支持过渡方向)
      rippleEffect //滴水效果(不支持过渡方向)
      pageCurl     //向上翻页效果
      pageUnCurl   //向下翻页效果
      cameraIrisHollowOpen  //相机镜头打开效果(不支持过渡方向)
      cameraIrisHollowClose //相机镜头关上效果(不支持过渡方向)
     */    
     /* 过渡方向
      kCATransitionFromRight
      kCATransitionFromLeft
      kCATransitionFromBottom 
      kCATransitionFromTop
      */
    // CATransition的使用 
    CATransition *anim = [CATransition animation];
    anim.type = @"cube"; // 动画过渡类型
    anim.subtype = kCATransitionFromTop; // 动画过渡方向
    anim.duration = 1; // 动画持续1s
    // 代理,动画执行完毕后会调用delegate的animationDidStop:finished:
    anim.delegate = self;
    1. UIView动画
          UIKit直接将动画集成到UIView类中,当内部的一些属性发生改变时,UIView将为这些改变提供动画支持.
          执行动画所需要的工作由UIView类自动完成,但仍要在希望执行动画时通知视图,为此需要将改变属性的代码放在[UIView beginAnimations:nil context:nil]和[UIView commitAnimations]之间
      常见方法解析:
          + (void)setAnimationDelegate:(id)delegate
      设置动画代理对象,当动画开始或者结束时会发消息给代理对象
          + (void)setAnimationWillStartSelector:(SEL)selector
      当动画即将开始时,执行delegate对象的selector,并且把beginAnimations:context:中传入的参数传进selector
          + (void)setAnimationDidStopSelector:(SEL)selector
      当动画结束时,执行delegate对象的selector,并且把beginAnimations:context:中传入的参数传进selector
      pastedGraphic.png
      //说明需要执行动画
    2. [UIView beginAnimations:nil context:nil];
    3. //设置动画持续时间
    4. [UIView setAnimationDuration:1];
    5. //设置转场动画
    6. [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
    7. //交换子视图的位置
    8. [self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
    9. //提交动画
    10. 10.[UIView commitAnimations];
      pastedGraphic.png

      UIView动画


      pastedGraphic.png
      + (void)setAnimationDuration:(NSTimeInterval)duration

  //动画的持续时间,秒为单位

  + (void)setAnimationDelay:(NSTimeInterval)delay

  //动画延迟delay秒后再开始

  + (void)setAnimationStartDate:(NSDate *)startDate

  //动画的开始时间,默认为now

  + (void)setAnimationCurve:(UIViewAnimationCurve)curve

  //动画的节奏控制,具体看下面的”备注”

  + (void)setAnimationRepeatCount:(float)repeatCount

  //动画的重复次数

  + (void)setAnimationRepeatAutoreverses:(BOOL)repeatAutoreverses

  //如果设置为YES,代表动画每次重复执行的效果会跟上一次相反

  + (void)setAnimationTransition:(UIViewAnimationTransition)transitionforView:(UIView *)view cache:(BOOL)cache pastedGraphic.png
Block动画


    + (void)animateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion
参数解析:
    duration:动画的持续时间
    delay:动画延迟delay秒后开始
    options:动画的节奏控制
    animations:将改变视图属性的代码放在这个block中
    completion:动画结束后,会自动调用这个block
    + (void)transitionWithView:(UIView *)view duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion
参数解析:
    duration:动画的持续时间
    view:需要进行转场动画的视图
    options:转场动画的类型
    animations:将改变视图属性的代码放在这个block中
    completion:动画结束后,会自动调用这个block
    + (void)transitionFromView:(UIView *)fromView toView:(UIView *)toView duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options completion:(void (^)(BOOL finished))completion
方法调用完毕后,相当于执行了下面两句代码:
    // 添加toView到父视图
[fromView.superview addSubview:toView];
    // 把fromView从父视图中移除
[fromView removeFromSuperview];
参数解析:
    duration:动画的持续时间
    options:转场动画的类型
    animations:将改变视图属性的代码放在这个block中
    completion:动画结束后,会自动调用这个block
UIImageView的帧动画
     UIImageView可以让一系列的图片在特定的时间内按顺序显示 .
相关属性解析: 
    animationImages:要显示的图片(一个装着UIImage的NSArray) .
    animationDuration:完整地显示一次animationImages中的所有图片所需的时间 .
    animationRepeatCount:动画的执行次数(默认为0,代表无限循环) 
相关方法解析: 
    - (void)startAnimating; 开始动画 .
    - (void)stopAnimating;  停止动画 .
    - (BOOL)isAnimating;  是否正在运行动画.
UIActivityIndicatorView
    是一个旋转进度轮,可以用来告知用户有一个操作正在进行中,一般用initWithActivityIndicatorStyle初始化
方法解析:
    - (void)startAnimating;开始动画
    - (void)stopAnimating;  停止动画
    - (BOOL)isAnimating;  是否正在运行动画
UIActivityIndicatorViewStyle有3个值可供选择:
    UIActivityIndicatorViewStyleWhiteLarge   //大型白色指示器    
    UIActivityIndicatorViewStyleWhite      //标准尺寸白色指示器    
    UIActivityIndicatorViewStyleGray    //灰色指示器,用于白色背景

 

UIView动画UIView Animation总结

http://www.cocoachina.com/ios/20170710/19794.html

本文为CocoaChina网友嘿o大远投稿

今天总结一下UIView动画就是 UiView动画是基于高层API封装进行封装的,对UIView的属性进行修改时候所产生的动画.

基本动画

下面两种方法是最常用的两种.

1
2
+ (void)animateWithDuration:(NSTimeInterval)duration 
                 animations:(void (^)(void))animations

animations 修改View属性的Block 下面是支持修改的属性

1
2
3
4
5
6
7
@property frame
@property bounds
@property center
@property transform
@property alpha
@property backgroundColor
@property contentStretch
1
2
3
+ (void)animateWithDuration:(NSTimeInterval)duration 
                 animations:(void (^)(void))animations 
                 completion:(void (^ __nullable)(BOOL finished))completion

completion 动画完成block

BOOL finished 表示动画是否完成

继续

1
2
3
4
5
+ (void)animateWithDuration:(NSTimeInterval)duration
                      delay:(NSTimeInterval)delay 
                      options:(UIViewAnimationOptions)options 
                      animations:(void (^)(void))animations 
                      completion:(void (^ __nullable)(BOOL finished))completion

delay 延迟执行时间

options 动画效果枚举 ,下面是全部枚举的说明

动画效果相关

 

1
2
3
4
5
6
7
8
9
10
UIViewAnimationOptionLayoutSubviews            //提交动画的时候布局子控件,表示子控件将和父控件一同动画。
UIViewAnimationOptionAllowUserInteraction      //动画时允许用户交流,比如触摸
UIViewAnimationOptionBeginFromCurrentState     //从当前状态开始动画
UIViewAnimationOptionRepeat                    //动画无限重复
UIViewAnimationOptionAutoreverse               //执行动画回路,前提是设置动画无限重复
UIViewAnimationOptionOverrideInheritedDuration //忽略外层动画嵌套的执行时间
UIViewAnimationOptionOverrideInheritedCurve    //忽略外层动画嵌套的时间变化曲线
UIViewAnimationOptionAllowAnimatedContent      //通过改变属性和重绘实现动画效果,如果key没有提交动画将使用快照
UIViewAnimationOptionShowHideTransitionViews   //用显隐的方式替代添加移除图层的动画效果
UIViewAnimationOptionOverrideInheritedOptions  //忽略嵌套继承的选项

时间函数曲线相关

1
2
3
4
UIViewAnimationOptionCurveEaseInOut            //时间曲线函数,由慢到快
UIViewAnimationOptionCurveEaseIn               //时间曲线函数,由慢到特别快
UIViewAnimationOptionCurveEaseOut              //时间曲线函数,由快到慢
UIViewAnimationOptionCurveLinear               //时间曲线函数,匀速

转场动画相关的

1
2
3
4
5
6
7
8
UIViewAnimationOptionTransitionNone            //无转场动画
UIViewAnimationOptionTransitionFlipFromLeft    //转场从左翻转
UIViewAnimationOptionTransitionFlipFromRight   //转场从右翻转
UIViewAnimationOptionTransitionCurlUp          //上卷转场
UIViewAnimationOptionTransitionCurlDown        //下卷转场
UIViewAnimationOptionTransitionCrossDissolve   //转场交叉消失
UIViewAnimationOptionTransitionFlipFromTop     //转场从上翻转
UIViewAnimationOptionTransitionFlipFromBottom  //转场从下翻转

弹簧动画

1
2
3
4
5
6
7
+ (void)animateWithDuration:(NSTimeInterval)duration 
                      delay:(NSTimeInterval)delay 
                      usingSpringWithDamping:(CGFloat)dampingRatio 
                      initialSpringVelocity:(CGFloat)velocity 
                      options:(UIViewAnimationOptions)options
                      animations:(void (^)(void))animations 
                      completion:(void (^ __nullable)(BOOL finished))completion

dampingRatio 弹簧的阻尼 如果为1动画则平稳减速动画没有振荡。 这里值为 0~1

velocity 弹簧的速率。数值越小,动力越小,弹簧的拉伸幅度就越小。反之相反。比如:总共的动画运行距离是200 pt,你希望每秒 100pt 时,值为 0.5;

例子

1
2
3
4
5
6
7
8
9
[UIView animateWithDuration:2
                      delay:2
     usingSpringWithDamping:.5
      initialSpringVelocity:.5
                    options:UIViewAnimationOptionRepeat
                animations:^{
   view.center = self.view.center;
} completion:^(BOOL finished) {   
}];

1444134-936f102da6e4037d.gif

过渡动画

 

1
2
3
4
5
+ (void)transitionWithView:(UIView *)view 
                  duration:(NSTimeInterval)duration 
                  options:(UIViewAnimationOptions)options
                  animations:(void (^ __nullable)(void))animations 
                  completion:(void (^ __nullable)(BOOL finished))completion

view 参与转换的视图

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[self.view addSubview:view];
view.center = self.view.center;
view.backgroundColor = [UIColor redColor];
UIView *view_1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
view_1.backgroundColor = [UIColor yellowColor];
[UIView transitionWithView:view 
                  duration:3      
                  options:UIViewAnimationOptionTransitionCurlUp 
                  animations:^{
                  [view addSubview:view_1];      
} completion:^(BOOL finished) {        
}];

1444134-3884cded6d157a53.gif

继续

1
2
3
4
5
+ (void)transitionFromView:(UIView *)fromView
                    toView:(UIView *)toView 
                    duration:(NSTimeInterval)duration 
                    options:(UIViewAnimationOptions)options 
                    completion:(void (^ __nullable)(BOOL finished))completion

fromView 一开始的视图

toView 转换后的视图

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
UIView *baseView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[self.view addSubview:baseView];
baseView.center = self.view.center;
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[baseView addSubview:view];
view.backgroundColor = [UIColor redColor];
UIView *view_1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
view_1.backgroundColor = [UIColor yellowColor];
[UIView transitionFromView:view
                    toView:view_1 
                    duration:2 
                    options:UIViewAnimationOptionTransitionFlipFromLeft completion:^(BOOL finished) {    
}];

1444134-8514c630f8bbef73.gif

关键帧动画

1
2
3
4
5
6
7
8
+ (void)animateKeyframesWithDuration:(NSTimeInterval)duration
                              delay:(NSTimeInterval)delay 
                              options:(UIViewKeyframeAnimationOptions)options 
                              animations:(void (^)(void))animations
                               completion:(void (^ __nullable)(BOOL finished))completion
+ (void)addKeyframeWithRelativeStartTime:(double)frameStartTime 
                        relativeDuration:(double)frameDuration 
                        animations:(void (^)(void))animations

duration 总持续时间

UIViewKeyframeAnimationOptions options 枚举 下面说明

frameStartTime 相对开始时间

frameDuration 相对持续时间

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 50, 50)];
view.backgroundColor = [UIColor orangeColor];
[self.view addSubview:view];
[UIView animateKeyframesWithDuration:3 delay:3 options:UIViewKeyframeAnimationOptionRepeat animations:^{
    [UIView addKeyframeWithRelativeStartTime:0 relativeDuration:.3 animations:^{
            view.frame = CGRectMake(20, 100, 100, 100);
    }];
     [UIView addKeyframeWithRelativeStartTime:.3 relativeDuration:.6 animations:^{
            view.frame = CGRectMake(60, 100, 80, 80);
    }];
    [UIView addKeyframeWithRelativeStartTime:.6 relativeDuration:1 animations:^{
            view.frame = CGRectMake(20, 20, 50, 50);
    }];
} completion:^(BOOL finished) {
}];

1444134-4d395d700c047416.gif

UIViewKeyframeAnimationOptions

1
2
3
4
5
6
    UIViewKeyframeAnimationOptionLayoutSubviews        //提交动画的时候布局子控件,表示子控件将和父控件一同动画。
    UIViewKeyframeAnimationOptionAllowUserInteraction  //动画时允许用户交流,比如触摸    UIViewKeyframeAnimationOptionBeginFromCurrentState     //从当前状态开始动画
    UIViewKeyframeAnimationOptionRepeat                //动画无限重复
    UIViewKeyframeAnimationOptionAutoreverse           //执行动画回路,前提是设置动画无限重复
    UIViewKeyframeAnimationOptionOverrideInheritedDuration //忽略外层动画嵌套的执行时间
    UIViewKeyframeAnimationOptionOverrideInheritedOptions  //忽略嵌套继承的选项

关键帧动画独有

1
2
3
4
5
    UIViewKeyframeAnimationOptionCalculationModeLinear     //选择使用一个简单的线性插值计算的时候关键帧之间的值。
    UIViewKeyframeAnimationOptionCalculationModeDiscrete   //选择不插入关键帧之间的值,而是直接跳到每个新的关键帧的值。
    UIViewKeyframeAnimationOptionCalculationModePaced      //选择计算中间帧数值算法使用一个简单的节奏。这个选项的结果在一个均匀的动画。
    UIViewKeyframeAnimationOptionCalculationModeCubic      //选择计算中间帧使用默认卡特莫尔罗花键,通过关键帧的值。你不能调整该算法的参数。 这个动画好像会更圆滑一些..
    UIViewKeyframeAnimationOptionCalculationModeCubicPaced //选择计算中间帧使用立方计划而忽略的时间属性动画。相反,时间参数计算隐式地给动画一个恒定的速度。

剩下两个操作

1
2
3
4
5
+ (void)performSystemAnimation:(UISystemAnimation)animation 
                       onViews:(NSArray *)views
                       options:(UIViewAnimationOptions)options 
                       animations:(void (^ __nullable)(void))parallelAnimations completion:(void (^ __nullable)(BOOL finished))completion
+ (void)performWithoutAnimation:(void (NS_NOESCAPE ^)(void))actionsWithoutAnimation

1.删除视图上的子视图 animation这个枚举只有一个删除值...

views操作的view 这会让那个视图变模糊、收缩和褪色, 之后再给它发送 removeFromSuperview 方法。

2.在动画block中不执行动画的代码.

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 50, 50)];
    view.backgroundColor = [UIColor orangeColor];
    UIView *view_1 = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 20, 20)];
    [view addSubview:view_1];
    view_1.backgroundColor = [UIColor redColor];
    [self.view addSubview:view];
    [UIView animateKeyframesWithDuration:3 delay:3 options:UIViewKeyframeAnimationOptionRepeat|UIViewKeyframeAnimationOptionAutoreverse animations:^{
        view.frame = CGRectMake(100, 100, 50, 50);
        [UIView performWithoutAnimation:^{
            view.backgroundColor = [UIColor blueColor];
        }];
    } completion:^(BOOL finished) {
    }];
    [UIView performSystemAnimation:UISystemAnimationDelete 
                           onViews:@[view_1] 
                           options:0 
                           animations:^{
        view_1.alpha = 0;
    } completion:^(BOOL finished) {
    }];

1444134-73db41a16ffa9023.gif

 
 
posted @ 2019-03-21 18:01  sundaysios  阅读(145)  评论(0编辑  收藏  举报