您的位置:首页 > 其它

核心动画——Core Animation

2016-10-31 09:59 225 查看

一. CALayer

(一). CALayer简介

在iOS中,你能看得见摸得着的东西基本上都是UIView,比如一个按钮、一个文本标签、一个文本输入框、一个图标等等,这些都是UIView,其实UIView之所以能显示在屏幕上,完全是因为它内部的一个图层,在创建UIView对象时,UIView内部会自动创建一个图层(即CALayer对象),通过UIView的layer属性可以访问这个层,要注意的是,这个默认的层不允许重新创建,但可以往层里面添加子层,UIView可以通过addSubview:方法添加子视图,当UIView需要显示到屏幕上时,会调用drawRect:方法进行绘图,并且会将所有内容绘制在自己的图层上,绘图完毕后,系统会将图层拷贝到屏幕上,于是就完成了UIView的显示,换句话说,UIView本身不具备显示的功能,是它内部的层才有显示功能。

(二). CALayer的基本属性

// 宽度和高度
@property CGRect bounds;

// 位置(默认指中点,具体由anchorPoint决定)
@property CGPoint position;

// 锚点(x,y的范围都是0-1),决定了position的含义
@property CGPoint anchorPoint;

// 背景颜色(CGColorRef类型)
@property CGColorRef backgroundColor;

// 形变属性
@property CATransform3D transform;

// 边框颜色(CGColorRef类型)
@property CGColorRef borderColor;

// 边框宽度
@property CGFloat borderWidth;

// 圆角半径
@property CGColorRef borderColor;

// 内容(比如设置为图片CGImageRef)
@property(retain) id contents;


X/Y/Z坐标轴图



(三). 关于CALayer的疑惑

所属框架

CALayer是定义在QuartzCore.framework中的;CGImageRef、CGColorRef两种数据类型是定义在CoreGraphics.framework中的;UIColor、UIImage是定义在UIKit.framework中的

跨平台性

QuartzCore框架和CoreGraphics框架是可以跨平台使用的,在iOS和Mac OS X上都能使用,但是UIKit只能在iOS中使用,不能在Mac OS X上使用,为了保证可移植性,QuartzCore不能使用UIImage、UIColor,只能使用CGImageRef、CGColorRef

通过CALayer,就能做出跟UIImageView一样的界面效果

UIView和CALayer的选择

UIView与CALayer比较,UIView多了一个事件处理的功能。也就是说,CALayer不能处理用户的触摸事件,而UIView可以。所以如果显示出来的东西需要跟用户进行交互的话,选择UIView;如果不需要跟用户进行交互,选择UIView或者CALayer都可以。当然,CALayer的性能会高一些,因为它少了事件处理的功能,更加轻量级。如果两个UIView是父子关系,那么它们内部的CALayer也是父子关系。

(四). position和anchorPoint

position和anchorPoint简单介绍

@property CGPoint position;

用来设置CALayer在父层中的位置

以父层的左上角为原点(0, 0)

@property CGPoint anchorPoint;

称为“定位点”、“锚点”

决定着CALayer身上的哪个点会在position属性所指的位置

以自己的左上角为原点(0, 0)

它的x、y取值范围都是0~1,默认值为(0.5, 0.5)

position和anchorPoint的联系

提示: CALayer的锚点anchorPoint决定了位置点position是CALayer身上的哪个点,在开发中一般先确定锚点再确定位置

例如: 假定CALayer的尺寸为50*50,把CALayer的position设置为(100,100);

当CALayer的anchorPoint设置为(0,0),CALayer身上的(0,0)点就是position所在点;

当CALayer的anchorPoint设置为(0.5,0.5),CALayer身上的(25,25)点就是position所在点;

当CALayer的anchorPoint设置为(1,1),CALayer身上的(50,50)点就是position所在点;

当CALayer的anchorPoint设置为(0.5,0),CALayer身上的(25,0)点就是position所在点;

当CALayer的anchorPoint设置为(1,0.5),CALayer身上的(50,25)点就是position所在点。

(五). 隐式动画

每一个UIView内部都默认关联着一个CALayer,我们可称这个Layer为Root Layer(根层或主层)

所有的非Root Layer,也就是手动创建的CALayer对象,都存在着隐式动画,根层没有隐身动画

什么是隐式动画?当对非Root Layer的部分属性进行修改时,默认会自动产生一些动画效果,而这些属性称为Animatable Properties(可动画属性)

常见的Animatable Properties:

bounds:用于设置CALayer的宽度和高度。修改这个属性会产生缩放动画

backgroundColor:用于设置CALayer的背景色。修改这个属性会产生背景色的渐变动画

position:用于设置CALayer的位置。修改这个属性会产生平移动画

要关闭默认的隐式动画,可以通过动画事务(CATransaction)关闭默认的隐式动画效果

[CATransaction begin];

[CATransaction setDisableActions:YES];

self.myview.layer.position = CGPointMake(10, 10);

[CATransaction commit];

(六). CALayer的基本使用

1. 图层的基本使用

提示: _myView是自定义的UIView

- (void)myViewLayer {
// 圆角半径
_myView.layer.cornerRadius = 50;

// 阴影,阴影跟随圆角半径的改变而改变
// Opacity:设置不透明度
_myView.layer.shadowOpacity = 1;
// 设置阴影偏移量
_myView.layer.shadowOffset = CGSizeMake(10, 10);
// 设置阴影颜色,注意:图层的颜色都是核心绘图框架,CGColor
_myView.layer.shadowColor = [[UIColor redColor] CGColor];
// 设置阴影的半径
_myView.layer.shadowRadius = 10;

// 边框
// 边框宽度
_myView.layer.borderWidth = 1;
// 边框颜色
_myView.layer.borderColor = [[UIColor blueColor] CGColor];
}


2. 图片裁剪成圆形

提示: _imageView是自定义的UIImageView

- (void)imageLayer {
// 设置主图层圆角半径
_imageView.layer.cornerRadius = 50;

// 超出图层边框的全部裁剪掉
// 注意:因为图片不是画在主图层上的,所以设置主图层的属性不影响图片显示
_imageView.layer.masksToBounds = YES;

// 设置边框
_imageView.layer.borderWidth = 0.6;
_imageView.layer.borderColor = [[UIColor redColor] CGColor];

// 如何判断以后是否需要裁剪图片,就判断下需要显示图层的控件是否是正方形。
}


3. 图层的缩放

提示: _myView是自定义的UIView

- (void)transLayer {
// 图层的缩放
[UIView animateWithDuration:2 animations:^{

//        // 旋转
//        _myView.layer.transform = CATransform3DMakeRotation(M_PI, 1, 1, 0);
//        // 缩放
//        _myView.layer.transform = CATransform3DMakeScale(0.5, 0.5, 0.5);
//

// 使用KVO快速进行图层缩放与旋转
// 不要使用setValue:forKey:设置,因为有可能不能实现
[_myView.layer setValue:@(M_PI) forKeyPath:@"transform.rotation"];
[_myView.layer setValue:@0.5 forKeyPath:@"transform.scale"];

}];
}


4. Layer的其他属性

提示: _myView是自定义的UIView

- (void)transLayer {

// 设置图层背景颜色
//    _myView.layer.backgroundColor = [[UIColor blueColor] CGColor];
// 设置尺寸
_myView.layer.bounds = CGRectMake(0, 0, 150, 150);
// 设置位置,默认指图层中点,具体由anchorPoint决定
//    _myView.layer.position = CGPointMake(0, 0);
// 锚点(x,y的范围都是0-1),决定了position的含义
//    _myView.layer.anchorPoint = CGPointMake(0.3, 0);

// 设置图层内容(比如设置为图片CGImageRef)
UIImage *image = [UIImage imageNamed:@"阿狸头像"];
_myView.layer.contents = (id)image.CGImage;

// 可以添加子图层
CALayer *myLayer = [CALayer layer];
myLayer.backgroundColor = [[UIColor yellowColor] CGColor];
myLayer.bounds = CGRectMake(0, 0, 50, 50);
[_myView.layer addSublayer:myLayer];
}


5. 自定义图层的隐式动画

#import "ViewController.h"

// 计算弧度
#define angle2radion(angle) ((angle) / 180.0 * M_PI)

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIView *myView;

@property (strong, nonatomic) CALayer *myLayer;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

// 创建图层
_myLayer = [CALayer layer];
_myLayer.bounds = CGRectMake(0, 0, 100, 100);
_myLayer.position = CGPointMake(75, 173);
_myLayer.backgroundColor = [[UIColor redColor] CGColor];
[self.view.layer addSublayer:_myLayer];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

_myLayer.transform = CATransform3DMakeRotation(angle2radion(arc4random_uniform(360) + 1), 1, 1, 1);
_myLayer.position = CGPointMake(arc4random_uniform(200) + 50, arc4random_uniform(400) + 50);
_myLayer.cornerRadius = arc4random_uniform(50);
_myLayer.backgroundColor = [[self randomColor] CGColor];
_myLayer.borderWidth = arc4random_uniform(10);
_myLayer.borderColor = [[self randomColor] CGColor];

//    _myView.layer.transform = CATransform3DMakeRotation(angle2radion(arc4random_uniform(360) + 1), 1, 1, 1);
//    _myView.layer.position = CGPointMake(arc4random_uniform(200) + 50, arc4random_uniform(400) + 50);
//    _myView.layer.cornerRadius = arc4random_uniform(50);
//    _myView.layer.backgroundColor = [[self randomColor] CGColor];
//    _myView.layer.borderWidth = arc4random_uniform(10);
//    _myView.layer.borderColor = [[self randomColor] CGColor];

}

- (UIColor *)randomColor
{

CGFloat r = arc4random_uniform(256) / 255.0;
CGFloat b = arc4random_uniform(256) / 255.0;
CGFloat g = arc4random_uniform(256) / 255.0;

return [UIColor colorWithRed:r green:g blue:b alpha:1];
}

@end


二. Core Animation

(一). Core Animation简介

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

核心动画开发步骤

(1). 首先得有CALayer

(2). 初始化一个CAAnimation对象,并设置一些动画相关属性

(3). 通过调用CALayer的addAnimation:forKey:方法,增加CAAnimation对象到CALayer中,这样就能开始执行动画了

(4). 通过调用CALayer的removeAnimationForKey:方法可以停止CALayer中的动画

(二). 核心动画继承结构



(三). CAAnimation简介

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

属性说明:(前六个属性来自CAMediaTiming协议的属性)

duration:动画的持续时间

repeatCount:重复次数,无限循环可以设置HUGE_VALF或者MAXFLOAT

repeatDuration:重复时间

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

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

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

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

delegate:动画代理,用来监听动画的执行过程

fillMode属性值(要想fillMode有效,最好设置removedOnCompletion = NO)

kCAFillModeRemoved:这个是默认值,也就是说当动画开始前和动画结束后,动画对layer都没有影响,动画结束后,layer会恢复到之前的状态

kCAFillModeForwards:当动画结束后,layer会一直保持着动画最后的状态

kCAFillModeBackwards:在动画开始前,只需要将动画加入了一个layer,layer便立即进入动画的初始状态并等待动画开始。

kCAFillModeBoth:这个其实就是上面两个的合成。动画加入后开始之前,layer便处于动画初始状态,动画结束后layer保持动画最后的状态

速度控制函数(CAMediaTimingFunction)

kCAMediaTimingFunctionLinear(线性):匀速,给你一个相对静态的感觉

kCAMediaTimingFunctionEaseIn(渐进):动画缓慢进入,然后加速离开

kCAMediaTimingFunctionEaseOut(渐出):动画全速进入,然后减速的到达目的地

kCAMediaTimingFunctionEaseInEaseOut(渐进渐出):动画缓慢的进入,中间加速,然后减速的到达目的地。这个是默认的动画行为。

动画的代理方法

// 动画开始前调用
- (void)animationDidStart:(CAAnimation *)anim;
// 动画结束后调用
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag;


(四). CAPropertyAnimation简介

CAPropertyAnimation是CAAnimation的子类,也是个抽象类,要想创建动画对象,应该使用它的两个子类:CABasicAnimation,CAKeyframeAnimation

属性说明:

keyPath:通过指定CALayer的一个属性名称为keyPath(NSString类型),并且对CALayer的这个属性的值进行修改,达到相应的动画效果。比如,指定@“position”为keyPath,就修改CALayer的position属性的值,以达到平移的动画效果

(五). CABasicAnimation简介

CABasicAnimation(基本动画),是CAPropertyAnimation的子类

属性说明:

fromValue:keyPath相应属性的初始值

toValue:keyPath相应属性的结束值

动画过程说明:

随着动画的进行,在长度为duration的持续时间内,keyPath相应属性的值从fromValue渐渐地变为toValue,keyPath的内容是CALayer的可动画Animatable属性,如果fillMode=kCAFillModeForwards同时removedOnComletion=NO,那么在动画执行完毕后,图层会保持显示动画执行后的状态。但在实质上,图层的属性值还是动画执行前的初始值,并没有真正被改变。

CABasicAnimation基本使用

动画效果:触碰屏幕,开始心跳

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

// 创建动画
CABasicAnimation *anim = [CABasicAnimation animation];

// 设置哪个属性要产生动画
anim.keyPath = @"transform.scale";
// 设置动画变化的值
anim.toValue = @0.5;

// 设置动画完成的时候不要移除动画,默认YES
anim.removedOnCompletion = NO;
// 设置动画执行完成要保持最新的效果
// 注意:要和removedOnCompletion配合使用才可以
anim.fillMode = kCAFillModeForwards;

// 设置动画次数
anim.repeatCount = 5;

// 给图片添加动画
// 注意:如果不单独设置anim.keyPath,就必须在方法里设置forKey
[_imageView.layer addAnimation:anim forKey:nil];

}

@end


(六). CAKeyframeAnimation简介

CAKeyframeAnimation关键帧动画,也是CAPropertyAnimation的子类,与CABasicAnimation的区别是:

CABasicAnimation只能从一个数值(fromValue)变到另一个数值(toValue),而CAKeyframeAnimation会使用一个NSArray保存这些数值

属性说明:

values:上述的NSArray对象。里面的元素称为“关键帧”(keyframe)。动画对象会在指定的时间(duration)内,依次显示values数组中的每一个关键帧

path:可以设置一个CGPathRef、CGMutablePathRef,让图层按照路径轨迹移动。path只对CALayer的anchorPoint和position起作用。如果设置了path,那么values将被忽略

keyTimes:可以为对应的关键帧指定对应的时间点,其取值范围为0到1.0,keyTimes中的每一个时间值都对应values中的每一帧。如果没有设置keyTimes,各个关键帧的时间是平分的。

CABasicAnimation可看做是只有2个关键帧的CAKeyframeAnimation。

CAKeyframeAnimation的基本使用

动画效果:在屏幕上画路径,图片跟着路径不停的跑

#import "DrawView.h"

#define angle2Radion(angle) (angle / 180.0 * M_PI)

@interface DrawView ()

@property  (nonatomic, strong) UIBezierPath *path;

@end

@implementation DrawView

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

UITouch *touch = [touches anyObject];

// 获取触控点
CGPoint curP = [touch locationInView:self];

// 创建路径
_path = [UIBezierPath bezierPath];

// 设置路径起点
[_path moveToPoint:curP];

}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

UITouch *touch = [touches anyObject];

// 获取触控点
CGPoint moveP = [touch locationInView:self];

// 设置路径下一个点
[_path addLineToPoint:moveP];

// 重绘
[self setNeedsDisplay];

}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];

//    anim.values = @[@(angle2Radion(-10)),@(angle2Radion(10)),@(angle2Radion(-10))];

// 设置需要动画属性
anim.keyPath = @"position";

// 设置动画路径
anim.path = _path.CGPath;

// 动画持续时间
anim.duration = 0.5;

// 设置动画次数
anim.repeatCount = MAXFLOAT;

[[[self.subviews firstObject] layer] addAnimation:anim forKey:nil];

}

- (void)drawRect:(CGRect)rect {
// Drawing code

// 描边
[_path stroke];

}

@end


(七). CAAnimationGroup简介

CAAnimationGroup动画组,是CAAnimation的子类,可以保存一组动画对象,将CAAnimationGroup对象加入层后,组中所有动画对象可以同时并发运行。

属性说明:

animations:用来保存一组动画对象的NSArray

默认情况下,一组动画对象是同时运行的,也可以通过设置动画对象的beginTime属性来更改动画的开始时间

CAAnimationGroup的基本使用

动画效果:触碰屏幕时,view同时做反转缩放移动的动画

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIView *myView;

@end

@implementation ViewController

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

CAAnimationGroup *animGroup = [CAAnimationGroup animation];

CABasicAnimation *scaleAnim = [CABasicAnimation animation];
scaleAnim.keyPath = @"transform.scale";
scaleAnim.toValue = @0.5;

CABasicAnimation *rotationAnim = [CABasicAnimation animation];
rotationAnim.keyPath = @"transform.rotation";
rotationAnim.toValue = @(arc4random_uniform(M_PI));

CABasicAnimation *positionAnim = [CABasicAnimation animation];
positionAnim.keyPath = @"position";
positionAnim.toValue = [NSValue valueWithCGPoint:CGPointMake(arc4random_uniform(200), arc4random_uniform(200))];

animGroup.animations = @[scaleAnim, rotationAnim, positionAnim];

[_myView.layer addAnimation:animGroup forKey:nil];

}

@end


(八). CATransition简介

CATransition过度动画又叫转场动画,是CAAnimation的子类,用于做转场动画,能够为层提供移出屏幕和移入屏幕的动画效果。iOS比Mac OS X的转场动画效果少一点。

UINavigationController就是通过CATransition实现了将控制器的视图推入屏幕的动画效果

动画属性:

type:动画过渡类型

subtype:动画过渡方向

startProgress:动画起点(在整体动画的百分比)

endProgress:动画终点(在整体动画的百分比)

CATransition的基本使用

动画效果:触碰屏幕时,图片动画切换

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController

static int name = 1;

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

if (name == 4) {
name = 1;
}

// 图片名称
NSString *imageName = [NSString stringWithFormat:@"%d",name++];

// 创建图片
_imageView.image = [UIImage imageNamed:imageName];

// 转场动画
CATransition *anim = [CATransition animation];

// 转场类型有:`fade', `moveIn', `push' and `reveal'
anim.type = @"pageCurl";

anim.duration = 2;

[_imageView.layer addAnimation:anim forKey:nil];

}

@end


(九). CALayer上动画的暂停与恢复

#pragma mark - 暂停CALayer的动画
-(void)pauseLayer:(CALayer*)layer
{
CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];

// 让CALayer的时间停止走动
layer.speed = 0.0;

// 让CALayer的时间停留在pausedTime这个时刻
layer.timeOffset = pausedTime;
}

#pragma mark - 恢复CALayer的动画
-(void)resumeLayer:(CALayer*)layer
{
CFTimeInterval pausedTime = layer.timeOffset;
// 1. 让CALayer的时间继续行走
layer.speed = 1.0;
// 2. 取消上次记录的停留时刻
layer.timeOffset = 0.0;
// 3. 取消上次设置的时间
layer.beginTime = 0.0;
// 4. 计算暂停的时间(这里也可以用CACurrentMediaTime()-pausedTime)
CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
// 5. 设置相对于父坐标系的开始时间(往后退timeSincePause)
layer.beginTime = timeSincePause;
}


(十). UIView动画与核心动画的区别

注意: 核心动画一切都是假象,并不会真正改变图层的属性值,如果以后做动画的时候不需要与用户交互,可以用核心动画。UIView必须需改属性值才能有动画效果。

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIView *myView;

@end

@implementation ViewController

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

CABasicAnimation *anim = [CABasicAnimation animation];

anim.keyPath = @"position";
anim.toValue = [NSValue valueWithCGPoint:CGPointMake(300, 300)];

// 取消反弹必须放在添加动画之前
anim.removedOnCompletion = NO;
anim.fillMode = kCAFillModeForwards;

// 设置代理
anim.delegate = self;

[_myView.layer addAnimation:anim forKey:nil];

//    [UIView animateWithDuration:0.25 animations:^{
//
//        _myView.layer.position = CGPointMake(300, 300);
//
//    } completion:^(BOOL finished) {
//
//        NSLog(@"%@",[NSValue valueWithCGPoint:_myView.layer.position]);
//
//    }];

}

// 动画结束后调用
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {

NSLog(@"%@",[NSValue valueWithCGPoint:_myView.layer.position]);
}

- (void)viewDidLoad {

NSLog(@"%@",[NSValue valueWithCGPoint:_myView.layer.position]);
}

@end


(十一). CALayer上动画的暂停和恢复

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIView *myView;

@end

@implementation ViewController

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

CABasicAnimation *anim = [CABasicAnimation animation];
anim.keyPath = @"transform.scale";
anim.toValue = @0.2;
anim.duration = 5;
anim.removedOnCompletion = NO;
anim.fillMode = kCAFillModeForwards;
[_myView.layer addAnimation:anim forKey:nil];

}

// 恢复动画
- (IBAction)pauser:(id)sender {

[self resumeLayer:_myView.layer];
}

// 暂停动画
- (IBAction)reusme:(id)sender {

[self pauseLayer:_myView.layer];

}

#pragma mark - 暂停CALayer的动画 -(void)pauseLayer:(CALayer*)layer { CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil]; // 让CALayer的时间停止走动 layer.speed = 0.0; // 让CALayer的时间停留在pausedTime这个时刻 layer.timeOffset = pausedTime; } #pragma mark - 恢复CALayer的动画 -(void)resumeLayer:(CALayer*)layer { CFTimeInterval pausedTime = layer.timeOffset; // 1. 让CALayer的时间继续行走 layer.speed = 1.0; // 2. 取消上次记录的停留时刻 layer.timeOffset = 0.0; // 3. 取消上次设置的时间 layer.beginTime = 0.0; // 4. 计算暂停的时间(这里也可以用CACurrentMediaTime()-pausedTime) CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime; // 5. 设置相对于父坐标系的开始时间(往后退timeSincePause) layer.beginTime = timeSincePause; }

@end


(十二). CADisplayLink计时器

CADisplayLink是一种以屏幕刷新频率触发的时钟机制,每秒钟执行大约60次左右

CADisplayLink是一个计时器,可以使绘图代码与视图的刷新频率保持同步,而NSTimer无法确保计时器实际被触发的准确时间

使用方法:

定义CADisplayLink并制定触发调用方法

将显示链接添加到主运行循环队列

使用实例(代码片)

#pragma mark - 定时器懒加载
- (CADisplayLink *)link {
if (_link == nil) {
// 初始化定时器
_link = [CADisplayLink displayLinkWithTarget:self selector:@selector(angleChange)];
// 定时器加入主运行循环
[_link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}
return _link;
}


三. CALayer补充

(一). CAGradientLayer(渐变图层)

属性

colors: 设置渐变颜色

locations: 设置渐变的定位点

startPoint: 设置渐变的开始点,取值0~1

endPoint: 设置渐变的结束点,取值0~1

type: 类型

使用实例

例子:图片折叠

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *topView;
@property (weak, nonatomic) IBOutlet UIImageView *downView;
@property (weak, nonatomic) IBOutlet UIView *dragView;
@property (strong, nonatomic) CAGradientLayer *gradLayer;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

// 1. 设置contentsRect属性,控制显示内容,取值0~1,0.5表示显示一半,1表示显示全部
_topView.layer.contentsRect = CGRectMake(0, 0, 1, 0.5);
_topView.layer.anchorPoint = CGPointMake(0.5, 1);

_downView.layer.contentsRect = CGRectMake(0, 0.5, 1, 0.5);
_downView.layer.anchorPoint = CGPointMake(0.5, 0);

// 2. 给最上面的view添加手势
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[_dragView addGestureRecognizer:pan];

// 3. 创建一个渐变图层
CAGradientLayer *gradLayer = [CAGradientLayer layer];
// 设置图层的尺寸和downView一样
gradLayer.frame = _downView.bounds;
// 设置图层透明度
gradLayer.opacity = 0;
// 设置渐变颜色
gradLayer.colors = @[(id)[[UIColor blackColor] CGColor], (id)[[UIColor clearColor] CGColor]];
//    // 设置渐变的定位点
//    gradLayer.locations = @[@0.5, @0.3, @0.1];
//    // 设置渐变的开始点,取值0~1
//    gradLayer.startPoint = CGPointMake(0.5, 0);
// 把渐变图层添加到最下面的downView
[_downView.layer addSublayer:gradLayer];
_gradLayer = gradLayer;
}

#pragma mark - 手势触发事件
- (void)pan:(UIPanGestureRecognizer *)pan {

// 获取偏移量
CGPoint transP = [pan locationInView:_dragView];

// 计算旋转角度,向下逆时针旋转
CGFloat angle = -transP.y / 200.0 * M_PI;

// 设置一个旋转对象
CATransform3D transform = CATransform3DIdentity;
// 增加旋转的立体感,远小近大,d代表距离
transform.m34 = -1 / 450.0;

// 给topView设置旋转
transform = CATransform3DRotate(transform, angle, 1, 0, 0);
_topView.layer.transform = transform;

// 4. 设置阴影渐变
_gradLayer.opacity = transP.y * 1 / 150.0;

// 5. 设置弹性效果
if (pan.state == UIGestureRecognizerStateEnded) {

// 弹簧效果的动画
// SpringWithDamping:弹性系数,越小,弹簧效果越明显
[UIView animateWithDuration:0.6 delay:0 usingSpringWithDamping:0.2 initialSpringVelocity:10 options:UIViewAnimationOptionCurveEaseInOut animations:^{

_topView.layer.transform = CATransform3DIdentity;
_gradLayer.opacity = 0;

} completion:^(BOOL finished) {

}];
}

}

@end


(二). CAReplicatorLayer(复制图层)

属性

instanceCount: 子层总数(包括原生子层)

instanceDelay: 复制子层动画延迟时长

instanceTransform: 复制子层形变(不包括原生子层),每个复制子层都是相对上一个。

instanceColor: 子层颜色,会和原生子层背景色冲突,因此二者选其一设置。

instanceRedOffset、instanceGreenOffset、instanceBlueOffset、instanceAlphaOffset`: 颜色通道偏移量,每个复制子层都是相对上一个的偏移量。

使用步骤

(1). 创建复制层

(2). 创建一个子图层

(3). 复制子图层

使用实例

例子:音量震动条

// 1. 创建复制图层
CAReplicatorLayer *repLayer = [CAReplicatorLayer layer];
repLayer.frame = _myView.bounds;
[_myView.layer addSublayer:repLayer];

// 2. 创建一个普通图层
CALayer *layer = [CALayer layer];
// 尺寸
layer.bounds = CGRectMake(0, 0, 30, 150);
// 锚点
layer.anchorPoint = CGPointMake(0.5, 1);
// 位置
layer.position = CGPointMake(25, _myView.bounds.size.height);
// 颜色
layer.backgroundColor = [[UIColor whiteColor] CGColor];
[repLayer addSublayer:layer];

// 3. 创建一个核心动画
CABasicAnimation *anim = [CABasicAnimation animation];
anim.keyPath = @"transform.scale.y";
anim.toValue = @0.1;
anim.repeatCount = MAXFLOAT;
anim.duration = 0.5;
// 设置反转动画,动画结束时执行逆动画
anim.autoreverses = YES;
[layer addAnimation:anim forKey:nil];

// 4. 设置复制图层
// instanceCount表示复制层里面子层总数,包括原始层
repLayer.instanceCount = 5;
// 设置复制子层偏移量,不包括原始层,相对于原始层x偏移
repLayer.instanceTransform = CATransform3DMakeTranslation(45, 0, 0);
// 设置复制层动画的延迟时间
repLayer.instanceDelay = 0.1;
// 设置图层的颜色,如果原始层设置不是白色,不要设置这个属性
repLayer.instanceColor = [[UIColor yellowColor] CGColor];
// 设置颜色偏移量
repLayer.instanceGreenOffset = -0.45;


(三). CAShapeLayer(形状图层)

CAShapeLayer继承于CALayer,可以使用CALayer的所有属性值;

CAShapeLayer需要贝塞尔曲线配合使用才有意义(也就是说才有效果)

使用CAShapeLayer(属于CoreAnimation)与贝塞尔曲线可以实现不在view的drawRect(继承于CoreGraphics走的是CPU,消耗的性能较大)方法中画出一些想要的图形

CAShapeLayer动画渲染直接提交到手机的GPU当中,相较于view的drawRect方法使用CPU渲染而言,其效率极高,能大大优化内存使用情况

具体实例

例子:QQ粘性效果

注意:要正常运行QQ粘性效果,必须关闭系统默认的约束

// 不使用系统默认的约束

self.view.translatesAutoresizingMaskIntoConstraints = NO;

#import "SJMButton.h"

// 最大圆心距离
#define kMaxDistance 80

@interface SJMButton ()

@property (nonatomic,strong) UIView *smallView;

@property (nonatomic, assign) CGFloat oldSmallViewRadius;

@property (nonatomic, weak) CAShapeLayer *shapeLayer;

@end

@implementation SJMButton

#pragma mark - 懒加载形状图层

- (CAShapeLayer *)shapeLayer {

if (_shapeLayer == nil) {
CAShapeLayer *layer = [CAShapeLayer layer];

_shapeLayer = layer;

// 注意:必须后设置颜色和添加
layer.fillColor = self.backgroundColor.CGColor;
[self.superview.layer insertSublayer:layer below:self.layer];

}
return _shapeLayer;
}

#pragma mark - 懒加载小圆

- (UIView *)smallView {

if (_smallView == nil) {
UIView *view = [[UIView alloc] init];
view.backgroundColor = self.backgroundColor;
_smallView = view;
// 小圆添加按钮的父控件上
[self.superview insertSubview:_smallView belowSubview:self];
}
return _smallView;
}

#pragma mark - 初始化

-(instancetype)initWithFrame:(CGRect)frame {

if (self = [super initWithFrame:frame]) {
[self setUp];
}
return self;
}

- (void)awakeFromNib {

[self setUp];
}

- (void)setUp {

CGFloat w = self.bounds.size.width;
_oldSmallViewRadius = w / 2;

// 设置按钮的圆角
self.layer.cornerRadius = w / 2;

// 添加Pan手势
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[self addGestureRecognizer:pan];

self.smallView.center = self.center;
self.smallView.bounds = self.bounds;
self.smallView.layer.cornerRadius = w / 2;

}

#pragma mark - PAN手势的触发事件

- (void)pan:(UIPanGestureRecognizer *)pan {

// 获取偏移量
CGPoint transP = [pan translationInView:self];

// 注意:修改形变并不会修改中心点
//self.transform = CGAffineTransformTranslate(self.transform, transP.x, transP.y);

// 修改按钮的center
CGPoint center = self.center;
center.x += transP.x;
center.y += transP.y;
self.center = center;

// 复位
[pan setTranslation:CGPointZero inView:self];

// 显示后面圆,后面圆的半径,随着两个圆心的距离不断增加而减小
//计算圆心距离
CGFloat d = [self distanceWithCenter:self.center otherCenter:self.smallView.center];

// 计算小圆的半径
CGFloat smallViewRadius = _oldSmallViewRadius - d / 10;

// 设置小圆的尺寸
self.smallView.bounds = CGRectMake(0, 0, smallViewRadius * 2, smallViewRadius * 2);
self.smallView.layer.cornerRadius = smallViewRadius;

/*-------------------------------描述不规则矩形----------------------------------*/

// 绘制不规则矩形,不能通过绘图,因为绘图只能在当前控件上画,超出部分不会显示
// 这里使用形状图层CAShapeLayer绘制

// 当圆心有距离但距离不大的时候调用
if (d > 0 && self.smallView.hidden == NO)
{
self.shapeLayer.path = [[self pathWithBigCirCleView:self smallCirCleView:self.smallView] CGPath];
}

// 当圆心距离大于最大距离的时候调用
// 效果是可以拖出来
if (d > kMaxDistance) {
// 隐藏小圆
self.smallView.hidden = YES;
// 移除不规则矩形
[self.shapeLayer removeFromSuperlayer];
self.shapeLayer = nil;
}

/*-------------------------------手指抬起的时候还原----------------------------------*/

if (pan.state == UIGestureRecognizerStateEnded)
{
if (d > kMaxDistance) {

// 展示gif动画
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.bounds];

NSMutableArray *arrM = [NSMutableArray array];
for (int i = 1; i < 9; i++) {
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d",i]];
[arrM addObject:image];
}

// 动画组
imageView.animationImages = arrM;
// 动画时间
imageView.animationDuration = 0.5;
// 动画次数
imageView.animationRepeatCount = 1;
// 开始动画
[imageView startAnimating];
[self addSubview:imageView];

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 把自己移除出父控件
[self removeFromSuperview];
});

} else {

// 移除不规则矩形
[self.shapeLayer removeFromSuperlayer];
self.shapeLayer = nil;

// 还原位置,有弹性效果
[UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.2 initialSpringVelocity:0 options:UIViewAnimationOptionCurveLinear animations:^{

self.center = self.smallView.center;

} completion:^(BOOL finished) {
self.smallView.hidden = NO;

}];

}

}

}

#pragma mark - 计算两点距离

- (CGFloat)distanceWithCenter:(CGPoint)center otherCenter:(CGPoint)otherCenter {

CGFloat offsetX = center.x - otherCenter.x;
CGFloat offsetY = center.y - otherCenter.y;

return sqrt(offsetX * offsetX + offsetY *offsetY);
}

#pragma mark - 描述两圆之间的矩形路线

- (UIBezierPath *)pathWithBigCirCleView:(UIView *)bigCirCleView  smallCirCleView:(UIView *)smallCirCleView
{
CGPoint bigCenter = bigCirCleView.center;
CGFloat x2 = bigCenter.x;
CGFloat y2 = bigCenter.y;
CGFloat r2 = bigCirCleView.bounds.size.width / 2;

CGPoint smallCenter = smallCirCleView.center;
CGFloat x1 = smallCenter.x;
CGFloat y1 = smallCenter.y;
CGFloat r1 = smallCirCleView.bounds.size.width / 2;

// 获取圆心距离
CGFloat d = [self distanceWithCenter:bigCenter otherCenter:smallCenter];

CGFloat sinθ = (x2 - x1) / d;

CGFloat cosθ = (y2 - y1) / d;

// 坐标系基于父控件
CGPoint pointA = CGPointMake(x1 - r1 * cosθ , y1 + r1 * sinθ);
CGPoint pointB = CGPointMake(x1 + r1 * cosθ , y1 - r1 * sinθ);
CGPoint pointC = CGPointMake(x2 + r2 * cosθ , y2 - r2 * sinθ);
CGPoint pointD = CGPointMake(x2 - r2 * cosθ , y2 + r2 * sinθ);
CGPoint pointO = CGPointMake(pointA.x + d / 2 * sinθ , pointA.y + d / 2 * cosθ);
CGPoint pointP =  CGPointMake(pointB.x + d / 2 * sinθ , pointB.y + d / 2 * cosθ);

UIBezierPath *path = [UIBezierPath bezierPath];

// A
[path moveToPoint:pointA];

// AB
[path addLineToPoint:pointB];

// 绘制BC曲线
[path addQuadCurveToPoint:pointC controlPoint:pointP];

// CD
[path addLineToPoint:pointD];

// 绘制DA曲线
[path addQuadCurveToPoint:pointA controlPoint:pointO];

return path;

}

@end


提示:粘性计算图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息