基于CAEmitterLayer的下雨、下雪、火焰、烟花粒子动画效果demo
demo源码地址:https://github.com/zhaoqianJoyce/ZQCAEmitterLayer
CAEmitterLayer是继承自CALayer的layer类,拥有很多属性,其中此demo用到的属性有:
emitterCells:是用来与CAEmitterLayer关联显示粒子效果的,是CAEmitterCell的实例化对象,必须有值;
emitterPosition:粒子排放位置,默认值是(0, 0);
emitterShape:粒子排放形状,默认值是kCAEmitterLayerPoint;
emitterSize:粒子排放的大小,取决于emitterShape,可忽略;
emitterMode:粒子排放模式,默认值是kCAEmitterLayerVolume;
renderMode:粒子渲染模式,默认值是kCAEmitterLayerUnordered.
CAEmitterCell继承自NSObject且遵循一定协议的类,拥有很多属性,其中此demo用到的属性有:
birthRate:粒子每秒产生个数;
lifetime:粒子的生命周期;
emissionRange:粒子排放的范围;
velocity:粒子的速度;
velocityRange:粒子速度变化值;
alphaSpeed:粒子生命周期内颜色变化速度;
contents:CAEmitterCell的内容,是CGImageRef类型。
核心代码
// 下雨、下雪
/**
* 设置emitterLayer的属性
*/
- (void)initEmitterLayerProperties {
self.emitterLayer.emitterSize = self.frame.size;
self.emitterLayer.emitterPosition = CGPointMake(self.frame.origin.x, self.frame.origin.y);
}
/**
* 设置emitterCell的属性并与emitterLayer关联显示动画效果
*
* @param weather 天气名称
*/
- (void)showWeather:(NSString *)weather {
CAEmitterCell *emitterCell = [CAEmitterCell emitterCell];
emitterCell.birthRate = 20.f;
emitterCell.lifetime = 100.f;
emitterCell.velocity = 10.f;
emitterCell.velocityRange = 3.f;
emitterCell.yAcceleration = 5.f;
emitterCell.emissionRange = 6 * M_2_PI;
emitterCell.contents = (__bridge id _Nullable)([UIImage imageNamed:weather].CGImage);
self.emitterLayer.emitterCells = @[emitterCell];
}
// 火焰
/**
* 设置emitterLayer的属性
*/
- (void)initEmitterLayerProperties {
self.emitterLayer.emitterSize = self.frame.size;
self.emitterLayer.emitterPosition = CGPointMake(self.frame.origin.x, self.frame.origin.y);
self.emitterLayer.emitterMode = kCAEmitterLayerPoints;
self.emitterLayer.renderMode = kCAEmitterLayerBackToFront;
}
/**
* 设置emitterCell的属性并与emitterLayer关联显示动画效果
*/
- (void)show {
CAEmitterCell *emitterCell = [CAEmitterCell emitterCell];
emitterCell.birthRate = 200.f;
emitterCell.lifetime = 10.f;
emitterCell.velocity = 10.f;
emitterCell.velocityRange = 15.f;
emitterCell.emissionRange = 2 * M_PI;
emitterCell.alphaSpeed -= 0.5f;
emitterCell.contents = (__bridge id _Nullable)([UIImage imageNamed:@"fire_selected"].CGImage);
self.emitterLayer.emitterCells = @[emitterCell];
}
// 烟花
/**
* 设置emitterLayer的属性
*/
- (void)initEmitterLayerProperties {
self.emitterLayer.emitterSize = self.frame.size;
self.emitterLayer.emitterPosition = CGPointMake(self.frame.origin.x, self.frame.origin.y);
self.emitterLayer.emitterMode = kCAEmitterLayerPoints;
self.emitterLayer.renderMode = kCAEmitterLayerBackToFront;
}
/**
* 设置emitterCell的属性并与emitterLayer关联显示动画效果
*/
- (void)show {
CAEmitterCell *emitterCell = [CAEmitterCell emitterCell];
emitterCell.birthRate = 50.f;
emitterCell.lifetime = 6.f;
emitterCell.velocity = 50.f;
emitterCell.velocityRange = 100.f;
emitterCell.emissionRange = 2 * M_PI;
emitterCell.alphaSpeed -= 0.5f;
emitterCell.contents = (__bridge id _Nullable)([UIImage imageNamed:@"fireworks_selected"].CGImage);
self.emitterLayer.emitterCells = @[emitterCell];
}