iOS动画之CALayer、CoreAnimatioin

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 228,505评论 6 533
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 98,556评论 3 418
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 176,463评论 0 376
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,009评论 1 312
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 71,778评论 6 410
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 55,218评论 1 324
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 43,281评论 3 441
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,436评论 0 288
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 48,969评论 1 335
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 40,795评论 3 354
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 42,993评论 1 369
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,537评论 5 359
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,229评论 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 34,659评论 0 26
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 35,917评论 1 286
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 51,687评论 3 392
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 47,990评论 2 374

推荐阅读更多精彩内容

  • 1 CALayer IOS SDK详解之CALayer(一) http://doc.okbase.net/Hell...
    Kevin_Junbaozi阅读 5,177评论 3 23
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥ios动画全貌。在这里你可以看...
    每天刷两次牙阅读 8,543评论 6 30
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌。在这里你可以看...
    F麦子阅读 5,131评论 5 13
  • 基础 核心动画是 iOS 和 MacOS 上的图形渲染和动画基础结构,用于为应用的视图和其他视觉元素设置动画。 核...
    davon阅读 1,931评论 0 8
  • 早起 5:45 体重56.4kg. 周五晚由于在妈妈家睡的,一切习惯都终止了
    早睡早起的习惯阅读 186评论 0 0