coreAnimation的基本使用

.h文件中定义一个枚举,有三个值,代表不同的动画效果

#import <UIKit/UIKit.h>

typedef NS_ENUM(NSUInteger, YSCAnimatinType) {
    YSCAnimatinTypeBasic,
    YSCAnimatinTypeKeyFrame,
    YSCAnimatinTypeKeyFramePath
};

@interface YSCLayerAnimationViewController : UIViewController

@end

.m文件中实现代码如下

//
//  YSCLayerAnimationViewController.m
//  动画
//
//  Created by 韩燕辉 on 16/9/20.
//  Copyright © 2016年 hyh. All rights reserved.
//

#import "YSCLayerAnimationViewController.h"

@implementation YSCLayerAnimationViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //画圆
    [self addShadowLayer];
    //添加蓝色圆
    CALayer *subLayer = [[CALayer alloc] init];
    subLayer.position = CGPointMake(50, 100);
    subLayer.bounds = CGRectMake(0, 0, 30, 30);
    subLayer.backgroundColor = [UIColor blueColor].CGColor;
    subLayer.masksToBounds = YES;
    subLayer.cornerRadius = 15;
    [self.view.layer addSublayer:subLayer];
    [subLayer setNeedsDisplay];
}
//画圆
- (void)addShadowLayer
{
    CALayer *shadowLayer = [[CALayer alloc] init];
    shadowLayer.position = CGPointMake(50, 100);
    shadowLayer.bounds = CGRectMake(0, 0, 30, 30);
    shadowLayer.cornerRadius = 15;
    shadowLayer.shadowColor = [UIColor yellowColor].CGColor;
    shadowLayer.shadowOffset = CGSizeMake(3, 3);
    shadowLayer.shadowOpacity = 0.5;
    shadowLayer.borderColor = [UIColor redColor].CGColor;
    shadowLayer.borderWidth = 2;
    [self.view.layer addSublayer:shadowLayer];
}
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
//    CGContextScaleCTM(ctx, 1, -1);
//    CGContextTranslateCTM(ctx, 0, -30);
//    CGImageRef imageRef = [UIImage imageNamed:@"tree.jpg"].CGImage;
//    CGContextDrawImage(ctx, CGRectMake(0, 0, 100, 100), imageRef);
//    CGImageRelease(imageRef);
}
- (void)addAnimationToLayerWithMode:(YSCAnimatinType)mode endPoint:(CGPoint)endPoint
{
    NSArray *subLayers = [self.view.layer sublayers];
    CALayer *animationLayer = [subLayers lastObject];
    
    if (YSCAnimatinTypeBasic == mode) {
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
        animation.fromValue = [NSValue valueWithCGPoint:CGPointMake(50, 100)];
        animation.toValue = [NSValue valueWithCGPoint:endPoint];
        animation.duration = 3;
        [animationLayer addAnimation:animation forKey:@"animaton-position"];
    } else if (YSCAnimatinTypeKeyFrame == mode) {
        CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        animation.values = [NSArray arrayWithObjects:[NSValue valueWithCGPoint:CGPointMake(50, 100)], [NSValue valueWithCGPoint:CGPointMake(150, 200)], [NSValue valueWithCGPoint:CGPointMake(50, 300)], [NSValue valueWithCGPoint:endPoint], nil];
        animation.duration = 4;
        animation.calculationMode = kCAAnimationPaced;//kCAAnimationLinear:每个keyValue间匀速  kCAAnimationCubic:平滑移动 kCAAnimationDiscrete:跳动,没有中间的滑动 kCAAnimationPaced:整个动画匀速,动画时间相关参数默认设置好 kCAAnimationCubicPaced:整个动画平滑匀速,动画时间相关参数默认设置好
        animation.keyTimes = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0], [NSNumber numberWithFloat:0.3], [NSNumber numberWithFloat:0.6], [NSNumber numberWithFloat:0.7], [NSNumber numberWithFloat:1.0], nil];//kCAAnimationDiscrete 需要多添一个time值,最后一个时间间隔用于动画结束后返回layer的初始状态或新设置的,kCAAnimationPaced和kCAAnimationCubicPaced对time属性不起作用,其他的keyValue数与time数相同,代表value的起始时间
        animation.delegate = self;//得放在addAnimation:之前,否则代理不会调用
        //存储当前位置在动画结束后使用
        [animation setValue:[NSValue valueWithCGPoint:endPoint] forKey:@"AnimationLocation"];
        [animationLayer addAnimation:animation forKey:@"animation-point"];
    } else if (YSCAnimatinTypeKeyFramePath == mode) {
        animationLayer.position = CGPointMake(350, 100);//加在添加动画前,先把layer的状态设为动画的最后状态,可避免动画完成后产生一个从初始位置到最终设置位置的快速隐式动画;若加在添加动画后,会产生一个从初始位置到最终设置位置的快速隐式动画,然后再开始添加的动画;采用代理的方式,在动画结束后,设置layer的最终状态(删除隐式动画),则可能出现一个从初始位置到最终设置位置的快速闪动。
        CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        CGMutablePathRef pathRef = CGPathCreateMutable();
        CGPathMoveToPoint(pathRef, NULL, 50, 100);
        CGPathAddCurveToPoint(pathRef, NULL, 70, 200, 230, 200, 250, 100);
        CGPathAddCurveToPoint(pathRef, NULL, 270, 200, 330, 200, 350, 100);
        animation.path = pathRef;
        CGPathRelease(pathRef);
        animation.duration = 3;
        //        animation.beginTime = CACurrentMediaTime() + 2;//此beginTime为图层的本地时间
        animation.calculationMode = kCAAnimationLinear;
        animation.keyTimes = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0], [NSNumber numberWithFloat:0.3], [NSNumber numberWithFloat:1.0], nil];//对于keyValues类型,标识各个value间的起始时间,个数为value数相同(kCAAnimationDiscrete会多一个);对于path则表示各个线段的起始时间,包括直线或曲线
        animation.delegate = self;//得放在addAnimation:之前,否则代理不会调用
        //存储当前位置在动画结束后使用
        [animation setValue:[NSValue valueWithCGPoint:CGPointMake(350, 100)] forKey:@"AnimationLocation"];
        [animationLayer addAnimation:animation forKey:@"animation-point"];
    }
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.view];
    NSArray *subLayers = [self.view.layer sublayers];
    CALayer *animationLayer = [subLayers lastObject];
    CAAnimation *animation = [animationLayer animationForKey:@"animation-point"];
    
    CFTimeInterval timeInterval = [animationLayer convertTime:CACurrentMediaTime() fromLayer:nil];
    NSLog(@"CurrentMediaTime:%f",timeInterval);
    
    if (animation) {
        if (0 == animationLayer.speed) {
            [self resumeAnimation];
        } else {
            [self pauseAnimation];
        }
    } else {
        NSInteger mode = YSCAnimatinTypeKeyFrame;
        [self addAnimationToLayerWithMode:mode endPoint:point];
        animationLayer.beginTime = 1;
    }
}
- (void)resumeAnimation
{
    NSArray *subLayers = [self.view.layer sublayers];
    CALayer *animationLayer = [subLayers lastObject];
    animationLayer.beginTime = CACurrentMediaTime() - animationLayer.timeOffset;
    animationLayer.timeOffset = 0;
    animationLayer.speed = 1;
}
- (void)pauseAnimation
{
    NSArray *subLayers = [self.view.layer sublayers];
    CALayer *animationLayer = [subLayers lastObject];
    CFTimeInterval timeInterval = [animationLayer convertTime:CACurrentMediaTime() fromLayer:nil];
    animationLayer.timeOffset = timeInterval;
    animationLayer.speed = 0;
}
#pragma mark - CAAnimationDelegate
- (void)animationDidStart:(CAAnimation *)anim
{

}
//停止动画
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    NSArray *subLayers = [self.view.layer sublayers];
    CALayer *animationLayer = [subLayers lastObject];
    
    //animationLayer.position = [[anim valueForKey:@"AnimationLocation"] CGPointValue];//直接设置最终位置,会产生一个从初始位置到最终设置位置的快速隐式动画,解决这个问题有两种办法:关闭图层隐式动画、设置动画图层为根图层
    
    //关闭图层隐式动画
    //开启事务
    [CATransaction begin];
    //禁用隐式动画
    [CATransaction setDisableActions:YES];
    animationLayer.position=[[anim valueForKey:@"AnimationLocation"] CGPointValue];//设置最终位置,否则,layer会回到初始位置,动画并没有改变layer。
    //提交事务
    [CATransaction commit];
}
@end

注意点,在YSCAnimatinTypeBasic中,动画结束的时候要设置这两个属性,才能保证结束的时候停留在动画结束的最后时刻

animation.removedOnCompletion = NO;
        animation.fillMode = kCAFillModeForwards;

YSCAnimatinTypeBasic

Snip20160920_1.png

YSCAnimatinTypeKeyFrame

Snip20160920_2.png

YSCAnimatinTypeKeyFramePath

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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,575评论 25 707
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥ios动画全貌。在这里你可以看...
    每天刷两次牙阅读 8,322评论 6 30
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌。在这里你可以看...
    F麦子阅读 5,004评论 5 13
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 10,517评论 6 13
  • 日复一日的早出晚归,与周围朋友的渐行渐远,夏季天气的低沉燥热,让我最近有有一些疲惫不堪,变得咆燥易怒。 有时候我需...
    石成玉_d24e阅读 340评论 0 2