美文网首页iOS学习笔记程序员iOS
iOS动画之CALayer、CoreAnimatioin

iOS动画之CALayer、CoreAnimatioin

作者: YW_Drenched | 来源:发表于2018-08-21 17:55 被阅读3次

CALayer

CALayer简介
  • 在iOS中,你能看得见摸得着的东西基本上都是UIView,比如一个按钮、一个文本框、一个Label,一 个图片等等,这些都是UIView
  • 其实UIView之所以能显示在屏幕上,完全是应为它内部的一个图层layer
  • 在创建UIView对象时,UIView内部会自动创建一个图层(CALayer),即UIView的layer属性
  • 当UIView需要显示到屏幕上时,会调用drawRect方法进行绘图,并且会将所有内容绘制在自己的图层 上,绘图完毕后,系统会将图层拷贝到屏幕上,于是就完成了UIView的显示
  • UIView本身不具备显示功能,是它内部的层才有显示功能
CALayer属性介绍
CALayer属性介绍

隐式属性动画的本质是这些属性的变动默认隐含了CABasicAnimation动画实现

  • anchorPoint属性是图层的锚点,范围在(0 ~ 1,0 ~ 1)表示在x、y轴的比例,这个点永远可以同position(中心点)重合,当图层中心点固定后,调整anchorPoint即可达到调整图层显示位置的作用(因为它永远和position重合),下图也能很好的诠释锚点的概念:
    锚点为(0.5,0.5) 锚点为(1,1)
CALayer示例代码
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self addLayer];
}

-(void)addLayer{
    CALayer *layer = [[CALayer alloc] init];
  
    CGSize size=[UIScreen mainScreen].bounds.size;
//    设置layer位置
    layer.position = CGPointMake(size.width/2, size.height/2);
//    设置layer大小
    layer.bounds = CGRectMake(0, 0, WIDTH, WIDTH);
//    设置圆弧,当为宽度一半时,则为圆形
    layer.cornerRadius = WIDTH / 2;
//    背景颜色
    layer.backgroundColor = [UIColor blueColor].CGColor;
//    阴影
    layer.shadowColor = [UIColor blackColor].CGColor;
    layer.shadowOffset = CGSizeMake(10, 10);
    layer.shadowOpacity = .6;

    [self.view.layer addSublayer:layer];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    CALayer *layer = self.view.layer.sublayers.firstObject;
    UITouch *touch = [touches anyObject];
    CGFloat width = layer.bounds.size.width;

    width==WIDTH ? (width = WIDTH * 4):(width = WIDTH);
    layer.position = [touch locationInView:self.view];
    layer.bounds = CGRectMake(0, 0, width, width);
    layer.cornerRadius = width / 2;
    
}
效果
CALayer绘图
  • 图层绘图有两种方法,不管使用哪种方法绘制完必须调用图层的setNeedDisplay方法
    1.通过图层代理drawLayer: inContext:方法绘制
    2.通过自定义图层drawInContext:方法绘制

  • 需要注意的是上面代码中绘制图片圆形裁切效果时如果不设置masksToBounds是无法显示圆形,但是对于其他图形却没有这个限制。原因就是当绘制一张图片到图层上的时候会重新创建一个图层添加到当前图层,这样一来如果设置了圆角之后虽然底图层有圆角效果,但是子图层还是矩形,只有设置了masksToBounds为YES让子图层按底图层剪切才能显示圆角效果。


#import "DrawLayerViewController.h"
#define WIDTH 100
@interface DrawLayerViewController ()<CALayerDelegate>


@end

@implementation DrawLayerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self addLayer];
}


-(void)addLayer{
    
    CALayer *showLayer = [[CALayer alloc] init];
    showLayer.position = self.view.center;
    showLayer.bounds = CGRectMake(0, 0, WIDTH, WIDTH);
    showLayer.shadowColor=[UIColor grayColor].CGColor;
    showLayer.shadowOffset=CGSizeMake(2, 1);
    showLayer.shadowOpacity=1;
    showLayer.borderWidth = 2;
    showLayer.borderColor = [UIColor orangeColor].CGColor;
    showLayer.cornerRadius = WIDTH / 2;
    [self.view.layer addSublayer:showLayer];
    
    CALayer *layer = [[CALayer alloc] init];
    layer.position = self.view.center;
    layer.bounds = CGRectMake(0, 0, WIDTH, WIDTH);
    layer.backgroundColor = [UIColor orangeColor].CGColor;
    layer.cornerRadius = WIDTH / 2;
    layer.masksToBounds = YES;
    layer.borderWidth = 2;
    layer.borderColor = [UIColor orangeColor].CGColor;
    layer.delegate = self;
    [self.view.layer addSublayer:layer];
    
    //必须调用此方法
    [layer setNeedsDisplay];
    
    
}

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx{
    CGContextSaveGState(ctx);
    
//    解决图像倒立问题
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -WIDTH);
    
    UIImage *image = [UIImage imageNamed:@"头像"];
    CGContextDrawImage(ctx, CGRectMake(0, 0, WIDTH, WIDTH), image.CGImage);
    
    CGContextRestoreGState(ctx);
}


@end
CALayer绘图效果

CoreAnimatioin

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


    CoreAnimatioin
  • CAAnimation:核心动画的基础类,不能直接使用,负责动画运行时间、速度的控制,本身实现了CAMediaTiming协议。

  • CAPropertyAnimation:属性动画的基类(通过属性进行动画设置,注意是可动画属性),不能直接使用。

  • CAAnimationGroup:动画组,动画组是一种组合模式设计,可以通过动画组来进行所有动画行为的统一控制,组中所有动画效果可以并发执行。

  • CATransition:转场动画,主要通过滤镜进行动画效果设置。

  • CABasicAnimation:基础动画,通过属性修改进行动画参数控制,只有初始状态和结束状态。

  • CAKeyframeAnimation:关键帧动画,同样是通过属性进行动画参数控制,但是同基础动画不同的是它可以有多个状态控制。

基础动画
#import "BaseAnimationViewController.h"

@interface BaseAnimationViewController ()<CAAnimationDelegate>
@property (nonatomic,strong)CALayer *layer;

@end

@implementation BaseAnimationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self animation];
    self.view.backgroundColor = [UIColor whiteColor];
}

-(void)animation{
    self.layer = [[CALayer alloc] init];
    self.layer.bounds = CGRectMake(0, 0, 30, 30);
    self.layer.position = CGPointMake(200, 100);
    self.layer.contents =(id) [UIImage imageNamed:@"叶子"].CGImage;
    self.layer.anchorPoint = CGPointMake(0.5, 0.6);
    [self.view.layer addSublayer:self.layer];
    
    
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = touches.anyObject;
    CGPoint point = [touch locationInView:self.view];
    [self moveToPoint:point];

}

// 移动动画
-(void)moveToPoint:(CGPoint)point{
    CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
    basicAnimation.duration = 5;
    basicAnimation.fromValue = [NSValue valueWithCGPoint:CGPointMake(200, 100)];
    basicAnimation.toValue = [NSValue valueWithCGPoint:point];
    basicAnimation.delegate = self;
    // 将终点存储起来
    [basicAnimation setValue:[NSValue valueWithCGPoint:point] forKey:@"animationStop"];
//    添加动画并给动画命名,后面可以通过名字获取动画
    [self.layer addAnimation:basicAnimation forKey:@"KCBasicAnimation_Translation"];
}


-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    //开启事务
    [CATransaction begin];
    //禁用隐式动画
    [CATransaction setDisableActions:YES];
//    将图层移动到终点
    self.layer.position = [[anim valueForKey:@"animationStop"] CGPointValue];
     //提交事务
    [CATransaction commit];
}



@end

关键帧动画
#import "KeyAnimationViewController.h"

@interface KeyAnimationViewController ()
@property (nonatomic,strong)CALayer *layer;

@end

@implementation KeyAnimationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.layer = [[CALayer alloc] init];
    self.layer.bounds = CGRectMake(0, 0, 30, 30);
    self.layer.position = CGPointMake(200, 100);
    self.layer.contents =(id) [UIImage imageNamed:@"叶子"].CGImage;
    self.layer.anchorPoint = CGPointMake(0.5, 0.6);
    [self.view.layer addSublayer:self.layer];
    [self creatKeyAnmition];
}

-(void)creatKeyAnmition{
    CAKeyframeAnimation *keyAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    NSValue *value1 = [NSValue valueWithCGPoint:self.layer.position];
    NSValue *value2 = [NSValue valueWithCGPoint:CGPointMake(300, 200)];
    NSValue *value3 = [NSValue valueWithCGPoint:CGPointMake(200, 350)];
    NSValue *value4 = [NSValue valueWithCGPoint:CGPointMake(300, 450)];
    
    keyAnimation.values = @[value1,value2,value3,value4];
    keyAnimation.duration = 5;
    [self.layer addAnimation:keyAnimation forKey:@"KCKeyframeAnimation_Position"];
    
    
}

@end
动画组
#import "GruopViewController.h"

@interface GruopViewController ()
@property (nonatomic,strong)CALayer *layer;

@end

@implementation GruopViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.layer = [[CALayer alloc] init];
    self.layer.position = CGPointMake(200, 100);
    self.layer.bounds = CGRectMake(0, 0, 30, 30);
    self.layer.contents = (id)[UIImage imageNamed:@"叶子"].CGImage;
    [self.view.layer addSublayer:self.layer];
    
    [self groupAnimation];
}

-(CABasicAnimation *)baseAnimation{
    CABasicAnimation *basicAnimation=[CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    
    CGFloat toValue=M_PI_2*3;
    basicAnimation.toValue=[NSNumber numberWithFloat:M_PI_2*3];
    
    //    basicAnimation.duration=6.0;
    basicAnimation.autoreverses=true;
    basicAnimation.repeatCount=HUGE_VALF;
    basicAnimation.removedOnCompletion=NO;
    
    [basicAnimation setValue:[NSNumber numberWithFloat:toValue] forKey:@"KCBasicAnimationProperty_ToValue"];
    
    return basicAnimation;
}

-(CAKeyframeAnimation *)keyAnimation{
    CAKeyframeAnimation *keyAnim = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    NSValue *key1=[NSValue valueWithCGPoint:_layer.position];//对于关键帧动画初始值不能省略
    NSValue *key2=[NSValue valueWithCGPoint:CGPointMake(300, 320)];
    NSValue *key3=[NSValue valueWithCGPoint:CGPointMake(200, 490)];
    NSValue *key4=[NSValue valueWithCGPoint:CGPointMake(370, 660)];
    keyAnim.values =@[key1,key2,key3,key4];
    keyAnim.duration = 8;
    
    return keyAnim;
}


-(void)groupAnimation{
    CAAnimationGroup *gruop = [CAAnimationGroup animation];
    CAKeyframeAnimation *keyAnim = [self keyAnimation];
    CABasicAnimation *basicAnim = [self baseAnimation];
    gruop.animations = @[keyAnim,basicAnim];
    gruop.duration = 8;
    [self.layer addAnimation:gruop forKey:nil];
}



@end

转场动画
  • 下表列出了常用的转场类型(注意私有API是苹果官方没有公开的动画类型,但是目前通过仍然可以使用):


    屏幕快照 2018-08-21 下午5.49.49.png
#import "TransitionViewController.h"

@interface TransitionViewController ()
@property (nonatomic,strong)UIImageView *imageView;

@property(nonatomic,assign)int index;

@end

@implementation TransitionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    //定义图片控件
    _imageView=[[UIImageView alloc]init];
    _imageView.frame=[UIScreen mainScreen].bounds;
    _imageView.contentMode=UIViewContentModeScaleAspectFit;
    _imageView.image=[UIImage imageNamed:@"img01"];//默认图片
    [self.view addSubview:_imageView];
    //添加手势
    UISwipeGestureRecognizer *leftSwipeGesture=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(leftSwipe:)];
    leftSwipeGesture.direction=UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:leftSwipeGesture];
    
    UISwipeGestureRecognizer *rightSwipeGesture=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(rightSwipe:)];
    rightSwipeGesture.direction=UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:rightSwipeGesture];
    
}


#pragma mark 向左滑动浏览下一张图片
-(void)leftSwipe:(UISwipeGestureRecognizer *)gesture{
    [self transitionAnimation:YES];
}

#pragma mark 向右滑动浏览上一张图片
-(void)rightSwipe:(UISwipeGestureRecognizer *)gesture{
    [self transitionAnimation:NO];
}

#pragma mark 转场动画
-(void)transitionAnimation:(BOOL)isNext{
    CATransition *transition = [[CATransition alloc] init];
    
    transition.type = @"rippleEffect";
    isNext?(transition.subtype = kCATransitionFromRight):(transition.subtype = kCATransitionFromLeft);
    transition.duration = .4f;
    self.imageView.image = [self getImage:isNext];
    [self.imageView.layer addAnimation:transition forKey:nil];
    
}

#pragma mark 取得当前图片
-(UIImage *)getImage:(BOOL)isNext{

    isNext?(self.index = self.index+1):(self.index = self.index-1);
    
    return [UIImage imageNamed:[NSString stringWithFormat:@"img0%d",self.index]];
}



@end

这里是参考文章,还有DEMO

相关文章

网友评论

    本文标题:iOS动画之CALayer、CoreAnimatioin

    本文链接:https://www.haomeiwen.com/subject/rmkjiftx.html