相關(guān)文獻(xiàn):
iOS CoreAnimation(一) - 基礎(chǔ)知識
iOS CoreAnimation(二) - CALayer/UIBezierPath
iOS CoreAnimation(三) - CAEmitterLayer粒子圖層
本文主要內(nèi)容:
1.了解CAEmitterLayer 類常?屬性與?法
2.了解CAEmitterCell 類常?屬性與?法
3.案例:實(shí)現(xiàn)發(fā)射粒子效果
4.案例:實(shí)現(xiàn)下雨場景
5.案例:實(shí)現(xiàn)QQ點(diǎn)贊效果
一、CAEmitterLayer常用屬性與方法
CAEmitterLayer的實(shí)現(xiàn)?性能的粒?引擎,被?來創(chuàng)建實(shí)現(xiàn)粒?動畫,?如煙霧,?,?等效果。
API_AVAILABLE(macos(10.6), ios(5.0), watchos(2.0), tvos(9.0))
@interface CAEmitterLayer : CALayer
// emitterCells 存放粒子類型
// 一個發(fā)射器可以存放多種的粒子類型,圓形/方形/星形...只需要告訴發(fā)射器即可
@property(nullable, copy) NSArray<CAEmitterCell *> *emitterCells;
// 產(chǎn)生粒子速率(默認(rèn)1.0)
@property float birthRate;
// 粒子的生命周期(默認(rèn)1.0)
@property float lifetime;
// 粒子發(fā)射源的位置,默認(rèn)(x:0, y:0, z:0)
@property CGPoint emitterPosition;
@property CGFloat emitterZPosition;
//發(fā)射源尺寸CAEmitterLayer實(shí)例的size/depth, 默認(rèn)(width:0, height:0, depth:0)
@property CGSize emitterSize;
@property CGFloat emitterDepth;
// 發(fā)射源的形狀:
/** 值:點(diǎn)形`point' (the default),
線形`line', 矩形`rectangle',
圓形`circle',
3D立體矩形`cuboid',
3D立體圓形`sphere'.
*/
@property(copy) CAEmitterLayerEmitterShape emitterShape;
// 發(fā)射源模式:
/** 值:`points'點(diǎn)模式,
`outline'輪廓模式(發(fā)射點(diǎn)邊界發(fā)射出來),
`surface'表面模式
`volume' 3D發(fā)射模式(the default).
*/
@property(copy) CAEmitterLayerEmitterMode emitterMode;
// 發(fā)射源渲染模式:
// 值:`unordered' (the default), `oldestFirst', `oldestLast', `backToFront' (i.e. sorted into Z order) and `additive'.
@property(copy) CAEmitterLayerRenderMode renderMode;
// 當(dāng)為true時,粒子被渲染成好像它們直接居住在層的超層的三維坐標(biāo)空間,而不是首先被平展到層的平面(默認(rèn)為NO)。
// 如果為true,則“filters”、“backgroundFilters”和陰影相關(guān)屬性的效果是未定義的。
@property BOOL preservesDepth;
// 乘以粒子定義的粒子速度(默認(rèn)為1.0)。
@property float velocity;
// 乘以粒子定義的粒子縮放(默認(rèn)為1.0)。
@property float scale;
// 乘以粒子定義的粒子自旋(默認(rèn)為1.0)。
@property float spin;
// 用于初始化隨機(jī)數(shù)生成器的種子(默認(rèn)為0)。
// 每一層都有自己的RNG狀態(tài)。對于均值為M,范圍為R的性質(zhì),性質(zhì)的隨機(jī)值均勻分布在區(qū)間[M - R/2, M + R/2]內(nèi)。
@property unsigned int seed;
@end
二、CAEmitterCell常?屬性與?法
CAEmitterCell定義的粒子樣式。
API_AVAILABLE(macos(10.6), ios(5.0), watchos(2.0), tvos(9.0))
@interface CAEmitterCell : NSObject <NSSecureCoding, CAMediaTiming>
{
@private
void *_attr[2];
void *_state;
uint32_t _flags;
}
// 創(chuàng)建實(shí)例
+ (instancetype)emitterCell;
// 粒子實(shí)現(xiàn)與CALayer定義的相同的屬性模型。
+ (nullable id)defaultValueForKey:(NSString *)key;
- (BOOL)shouldArchiveValueForKey:(NSString *)key;
// 粒子名稱,默認(rèn)為nil??梢詷?gòu)造多種粒子樣式,通過name去區(qū)分。
@property(nullable, copy) NSString *name;
// 是否可用,控制是否呈現(xiàn)此發(fā)射器中的粒子。
@property(getter=isEnabled) BOOL enabled;
// 每秒創(chuàng)建的發(fā)射的粒子數(shù)量。默認(rèn)值0.0
// 產(chǎn)生率
@property float birthRate;
// 每個發(fā)射的粒子生命周期(以秒為單位),指定為平均值和平均值的范圍。這兩個值默認(rèn)0.0
@property float lifetime; // 生命周期
@property float lifetimeRange; // 生命周期的范圍
// 發(fā)射粒子的緯度(弧度為單位),X軸與Z軸之間的夾角,默認(rèn)0.0
@property CGFloat emissionLatitude;
// 發(fā)射粒子的經(jīng)度(弧度為單位),X軸與Y軸之間的夾角,默認(rèn)0.0
@property CGFloat emissionLongitude;
// 發(fā)射角度(弧度為單位),默認(rèn)0.0。發(fā)射的物體均勻地分布在這個錐體上。
@property CGFloat emissionRange;
// 每個發(fā)射粒子平均速度,默認(rèn)為0.0
@property CGFloat velocity;
// 每個發(fā)射粒子速度范圍,默認(rèn)為0.0
@property CGFloat velocityRange;
// 應(yīng)用于發(fā)射粒子在對應(yīng)軸上的加速度矢量。默認(rèn)(0, 0, 0)
@property CGFloat xAcceleration;
@property CGFloat yAcceleration;
@property CGFloat zAcceleration;
/* The scale factor applied to each emitted object, defined as mean and
* range about the mean. Scale defaults to one, range to zero.
* Animatable. */
// 初始縮放比例,默認(rèn)1.0,比如一開始就放大2倍就寫2
@property CGFloat scale;
// 縮放范圍,默認(rèn)0.0
@property CGFloat scaleRange;
// 縮放速度
@property CGFloat scaleSpeed;
// 應(yīng)用于每個粒子的旋轉(zhuǎn)速度,定義為平均值和平均值的范圍。默認(rèn)為0。
@property CGFloat spin;
@property CGFloat spinRange;
/* The mean color of each emitted object, and the range from that mean
* color. `color' defaults to opaque white, `colorRange' to (0, 0, 0,
* 0). Animatable. */
// 粒子的顏色,默認(rèn)白色
@property(nullable) CGColorRef color;
// 以及粒子的顏色變化范圍,colorRange為(r:0, g:0, b:0, a:0)。
@property float redRange;
@property float greenRange;
@property float blueRange;
@property float alphaRange;
// 顏色變化速度,默認(rèn) (0, 0, 0, 0)
@property float redSpeed;
@property float greenSpeed;
@property float blueSpeed;
@property float alphaSpeed;
// 粒子內(nèi)容,默認(rèn)nil。通常是CGImageRef。
@property(nullable, strong) id contents;
// contents的大小,默認(rèn)為[0 0 1 1]
@property CGRect contentsRect;
// contents的縮放系數(shù)
@property CGFloat contentsScale;
// 渲染“contents”圖像時使用的過濾器參數(shù)。
@property(copy) NSString *minificationFilter;
@property(copy) NSString *magnificationFilter;
@property float minificationFilterBias;
// 粒子里面再套粒子,類似于tableViewCell里也能有tableView的Cell
@property(nullable, copy) NSArray<CAEmitterCell *> *emitterCells;
// 繼承屬性類似于layers。
@property(nullable, copy) NSDictionary *style;
@end
三、案例:實(shí)現(xiàn)發(fā)射粒子效果

#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) CAEmitterLayer * colorBallLayer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor blackColor];
[self setupEmitter];
}
- (void)setupEmitter {
UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width, 50)];
[self.view addSubview:label];
label.textColor = [UIColor whiteColor];
label.text = @"輕點(diǎn)或拖動來改變發(fā)射源位置";
label.textAlignment = NSTextAlignmentCenter;
//1.創(chuàng)建發(fā)射源,類似于UITableView
CAEmitterLayer *colorBallLayer = [CAEmitterLayer layer];
[self.view.layer addSublayer:colorBallLayer];
self.colorBallLayer = colorBallLayer;
//發(fā)射源尺寸colorBallLayer的frame
colorBallLayer.emitterSize = self.view.frame.size;
//發(fā)射源形狀
colorBallLayer.emitterShape = kCAEmitterLayerPoint;
//發(fā)射模式
colorBallLayer.emitterMode = kCAEmitterLayerPoints;
//粒子發(fā)射的中心點(diǎn).
colorBallLayer.emitterPosition = CGPointMake(self.view.layer.bounds.size.width, 0);
//2.設(shè)置Cell(粒子的樣式),類似于UITableViewCell
CAEmitterCell *colorBallCell = [CAEmitterCell emitterCell];
//粒子名稱
colorBallCell.name = @"ccCell";
//粒子的產(chǎn)生速率
colorBallCell.birthRate = 20.0f;
//粒子的生命周期
colorBallCell.lifetime = 10.0f;
//粒子速度
colorBallCell.velocity = 40.0f;
colorBallCell.velocityRange = 100.0;
colorBallCell.yAcceleration = 15.0f; // 粒子在Y軸上的加速矢量
// 發(fā)射粒子的緯度(弧度為單位),X軸與Z軸之間的夾角,默認(rèn)0.0
colorBallCell.emissionLatitude = M_PI;
// 發(fā)射角度(弧度為單位),默認(rèn)0.0。發(fā)射的物體均勻地分布在這個錐體上。
colorBallCell.emissionRange = M_PI_4;
colorBallCell.scale = 0.2;
colorBallCell.scaleRange = 0.1;
colorBallCell.scaleSpeed = 0.02;
//粒子的內(nèi)容
colorBallCell.contents = (id)[[UIImage imageNamed:@"circle_white"] CGImage]; // 一張圖片
//顏色變化
colorBallCell.color = [UIColor colorWithRed:0.5 green:0.0 blue:0.5 alpha:1.0].CGColor;
//粒子顏色改變范圍
colorBallCell.alphaRange = 0.8f;
colorBallCell.redRange = 1.0f;
colorBallCell.greenRange = 1.0f;
//粒子變化的速度
colorBallCell.blueSpeed = 1.0f;
colorBallCell.alphaSpeed = -0.1;
// 一個發(fā)射器可以存放多種的粒子類型,圓形/方形/星形...只需要告訴發(fā)射器即可
colorBallLayer.emitterCells = @[colorBallCell];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
CGPoint point = [self locationFromTouchEvent:event];
[self setBallInPsition:point];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
CGPoint point = [self locationFromTouchEvent:event];
[self setBallInPsition:point];
}
/**
* 獲取手指所在點(diǎn)
*/
- (CGPoint)locationFromTouchEvent:(UIEvent *)event{
UITouch * touch = [[event allTouches] anyObject];
return [touch locationInView:self.view];
}
/**
* 移動發(fā)射源到某個點(diǎn)上
*/
- (void)setBallInPsition:(CGPoint)position{
//創(chuàng)建基礎(chǔ)動畫(粒子放大過程)
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"emitterCells.colorBallCell.scale"];
// 改變粒子的縮放 0.2->0.5
anim.fromValue = @0.2;
anim.toValue = @0.5f;
anim.duration = 1.0;
//變化模式: 線性變化,動畫是勻速發(fā)生
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
//移動粒子的發(fā)射位置runloop
//事務(wù)性動畫,用來包裝隱式動畫
[CATransaction begin];
[CATransaction setDisableActions:YES];
[self.colorBallLayer addAnimation:anim forKey:nil];
[self.colorBallLayer setValue:[NSValue valueWithCGPoint:position] forKey:@"emitterPosition"];
[CATransaction commit];
}
@end
四、案例:實(shí)現(xiàn)下雨場景

#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) CAEmitterLayer * rainLayer;
@property (nonatomic, weak) UIImageView * imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setupUI];
[self setupEmitter];
}
- (void)setupUI {
// 背景圖片
UIImageView * imageView = [[UIImageView alloc]initWithFrame:self.view.frame];
[self.view addSubview:imageView];
self.imageView = imageView;
imageView.image = [UIImage imageNamed:@"rain"];
// 下雨按鈕
UIButton * startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[self.view addSubview:startBtn];
startBtn.frame = CGRectMake(20, self.view.bounds.size.height - 60, 80, 40);
startBtn.backgroundColor = [UIColor whiteColor];
[startBtn setTitle:@"雨停了" forState:UIControlStateNormal];
[startBtn setTitle:@"下雨" forState:UIControlStateSelected];
[startBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[startBtn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
[startBtn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
// 雨量按鈕
UIButton * rainBIgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[self.view addSubview:rainBIgBtn];
rainBIgBtn.tag = 100;
rainBIgBtn.frame = CGRectMake(140, self.view.bounds.size.height - 60, 80, 40);
rainBIgBtn.backgroundColor = [UIColor whiteColor];
[rainBIgBtn setTitle:@"下大點(diǎn)" forState:UIControlStateNormal];
[rainBIgBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[rainBIgBtn addTarget:self action:@selector(rainButtonClick:) forControlEvents:UIControlEventTouchUpInside];
UIButton * rainSmallBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[self.view addSubview:rainSmallBtn];
rainSmallBtn.tag = 200;
rainSmallBtn.frame = CGRectMake(240, self.view.bounds.size.height - 60, 80, 40);
rainSmallBtn.backgroundColor = [UIColor whiteColor];
[rainSmallBtn setTitle:@"太大了" forState:UIControlStateNormal];
[rainSmallBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[rainSmallBtn addTarget:self action:@selector(rainButtonClick:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)buttonClick:(UIButton *)sender {
if (!sender.selected) {
sender.selected = !sender.selected;
NSLog(@"雨停了");
// 停止下雨
[self.rainLayer setValue:@0.f forKeyPath:@"birthRate"];
}else{
sender.selected = !sender.selected;
NSLog(@"開始下雨了");
// 開始下雨
[self.rainLayer setValue:@1.f forKeyPath:@"birthRate"];
}
}
- (void)rainButtonClick:(UIButton *)sender {
NSInteger rate = 1;
CGFloat scale = 0.05;
if (sender.tag == 100) {
NSLog(@"下大了");
if (self.rainLayer.birthRate < 30) {
[self.rainLayer setValue:@(self.rainLayer.birthRate + rate) forKeyPath:@"birthRate"];
[self.rainLayer setValue:@(self.rainLayer.scale + scale) forKeyPath:@"scale"];
}
}else if (sender.tag == 200) {
NSLog(@"變小了");
if (self.rainLayer.birthRate > 1) {
[self.rainLayer setValue:@(self.rainLayer.birthRate - rate) forKeyPath:@"birthRate"];
[self.rainLayer setValue:@(self.rainLayer.scale - scale) forKeyPath:@"scale"];
}
}
}
- (void)setupEmitter {
// 1. 設(shè)置CAEmitterLayer
CAEmitterLayer * rainLayer = [CAEmitterLayer layer];
// 2.在背景圖上添加粒子圖層
[self.imageView.layer addSublayer:rainLayer];
self.rainLayer = rainLayer;
//3.發(fā)射形狀--線性
rainLayer.emitterShape = kCAEmitterLayerLine;
//發(fā)射模式
rainLayer.emitterMode = kCAEmitterLayerSurface;
//發(fā)射源大小
rainLayer.emitterSize = self.view.frame.size;
//發(fā)射源位置 y最好不要設(shè)置為0 最好<0
rainLayer.emitterPosition = CGPointMake(self.view.bounds.size.width * 0.5, -10);
// 2. 配置cell
CAEmitterCell * snowCell = [CAEmitterCell emitterCell];
//粒子內(nèi)容
snowCell.contents = (id)[[UIImage imageNamed:@"rain_white"] CGImage];
//每秒產(chǎn)生的粒子數(shù)量的系數(shù)
snowCell.birthRate = 25.f;
//粒子的生命周期
snowCell.lifetime = 20.f;
//speed粒子速度.圖層的速率。用于將父時間縮放為本地時間,例如,如果速率是2,則本地時間的進(jìn)度是父時間的兩倍。默認(rèn)值為1。
snowCell.speed = 10.f;
//粒子速度系數(shù), 默認(rèn)1.0
snowCell.velocity = 10.f;
//每個發(fā)射物體的初始平均范圍,默認(rèn)等于0
snowCell.velocityRange = 10.f;
//粒子在y方向的加速的
snowCell.yAcceleration = 1000.f;
//粒子縮放比例: scale
snowCell.scale = 0.1;
//粒子縮放比例范圍:scaleRange
snowCell.scaleRange = 0.f;
// 3.添加到圖層上
rainLayer.emitterCells = @[snowCell];
}
@end
五、案例:實(shí)現(xiàn)QQ點(diǎn)贊效果
- 點(diǎn)贊按鈕放大->縮?。篊AKeyFrameAnimation
- 放大之后,釋放一個圈的粒子效果:CAEmitterLayer
需要:1.自定義按鈕、2.重寫按鈕選中狀態(tài)、3.配置動畫

#import "ViewController.h"
#import "CCLikeButton.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
//添加點(diǎn)贊按鈕
CCLikeButton * btn = [CCLikeButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(200, 150, 30, 130);
[self.view addSubview:btn];
[btn setImage:[UIImage imageNamed:@"dislike"] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:@"like_orange"] forState:UIControlStateSelected];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)btnClick:(UIButton *)button {
if (!button.selected) { // 點(diǎn)贊
button.selected = !button.selected;
NSLog(@"點(diǎn)贊");
}else{ // 取消點(diǎn)贊
button.selected = !button.selected;
NSLog(@"取消贊");
}
}
@end
#import "CCLikeButton.h"
@interface CCLikeButton()
@property(nonatomic,strong)CAEmitterLayer *explosionLayer;
@end
@implementation CCLikeButton
- (void)awakeFromNib{
[super awakeFromNib];
//設(shè)置粒子效果
[self setupExplosion];
}
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self setupExplosion];
}
return self;
}
//設(shè)置粒子
- (void)setupExplosion {
// 1. 粒子
CAEmitterCell * explosionCell = [CAEmitterCell emitterCell];
explosionCell.name = @"explosionCell";
//透明值變化速度
explosionCell.alphaSpeed = -1.f;
//alphaRange透明值范圍
explosionCell.alphaRange = 0.10;
//生命周期
explosionCell.lifetime = 1;
//生命周期range
explosionCell.lifetimeRange = 0.1;
//粒子速度
explosionCell.velocity = 40.f;
//粒子速度范圍
explosionCell.velocityRange = 10.f;
//縮放比例
explosionCell.scale = 0.08;
//縮放比例range
explosionCell.scaleRange = 0.02;
//粒子圖片
explosionCell.contents = (id)[[UIImage imageNamed:@"spark_red"] CGImage];
// 2.發(fā)射源
CAEmitterLayer * explosionLayer = [CAEmitterLayer layer];
[self.layer addSublayer:explosionLayer];
self.explosionLayer = explosionLayer;
//發(fā)射院尺寸大小
self.explosionLayer.emitterSize = CGSizeMake(self.bounds.size.width + 40, self.bounds.size.height + 40);
//emitterShape表示粒子從什么形狀發(fā)射出來,圓形形狀
explosionLayer.emitterShape = kCAEmitterLayerCircle;
//emitterMode發(fā)射模型,輪廓模式,從形狀的邊界上發(fā)射粒子
explosionLayer.emitterMode = kCAEmitterLayerOutline;
//renderMode:渲染模式
explosionLayer.renderMode = kCAEmitterLayerOldestFirst;
//粒子cell 數(shù)組
explosionLayer.emitterCells = @[explosionCell];
}
-(void)layoutSubviews {
// 發(fā)射源位置
self.explosionLayer.position = CGPointMake(self.bounds.size.width * 0.5, self.bounds.size.height * 0.5);
[super layoutSubviews];
}
/**
* 選中狀態(tài) 實(shí)現(xiàn)縮放
*/
- (void)setSelected:(BOOL)selected {
[super setSelected:selected];
// 通過關(guān)鍵幀動畫實(shí)現(xiàn)縮放
CAKeyframeAnimation * animation = [CAKeyframeAnimation animation];
// 設(shè)置動畫路徑
animation.keyPath = @"transform.scale";
if (selected) {
// 從沒有點(diǎn)擊到點(diǎn)擊狀態(tài) 會有爆炸的動畫效果
animation.values = @[@1.5,@2.0, @0.8, @1.0];
animation.duration = 0.5;
//計算關(guān)鍵幀方式:
animation.calculationMode = kCAAnimationCubic;
//為圖層添加動畫
[self.layer addAnimation:animation forKey:nil];
// 讓放大動畫先執(zhí)行完畢 再執(zhí)行爆炸動畫
[self performSelector:@selector(startAnimation) withObject:nil afterDelay:0.25];
}else{
// 從點(diǎn)擊狀態(tài)normal狀態(tài) 無動畫效果 如果點(diǎn)贊之后馬上取消 那么也立馬停止動畫
[self stopAnimation];
}
}
// 沒有高亮狀態(tài)
- (void)setHighlighted:(BOOL)highlighted{
[super setHighlighted:highlighted];
}
/**
* 開始動畫
*/
- (void)startAnimation{
// 用KVC設(shè)置顆粒個數(shù)
[self.explosionLayer setValue:@1000 forKeyPath:@"emitterCells.explosionCell.birthRate"];
// 開始動畫
self.explosionLayer.beginTime = CACurrentMediaTime();
// 延遲停止動畫
[self performSelector:@selector(stopAnimation) withObject:nil afterDelay:0.15];
}
/**
* 動畫結(jié)束
*/
- (void)stopAnimation{
// 用KVC設(shè)置顆粒個數(shù)
[self.explosionLayer setValue:@0 forKeyPath:@"emitterCells.explosionCell.birthRate"];
//移除動畫
[self.explosionLayer removeAllAnimations];
}
- (void)drawRect:(CGRect)rect {
}
@end