1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > iOS---使用CAEmitterLayer制作发射粒子的特效

iOS---使用CAEmitterLayer制作发射粒子的特效

时间:2023-05-13 04:02:42

相关推荐

iOS---使用CAEmitterLayer制作发射粒子的特效

CAEmitterLayer是QuartzCore提供的粒子引擎, 可用于制作美观的粒子特效.

如下图是一个粒子特效的截图, 实际的动态效果会更好, 因为gif制作比较模糊就没有贴出来.

CAEmitterLayer

CAEmitterLayer与CAEAGLLayer类似, 如果放在UIView中则要重写UIView的layerClass方法:

@interface ViewCAEmitter : UIView@end@implementation ViewCAEmitter+ (Class)layerClass {return [CAEmitterLayer class];}// xxx@end

如果是在UIViewController中, 则直接在layer上添加CAEmitterLayer即可:

@implementation UIViewController- (void)setupCAEmitterLayer {_caEmitterLayer = [CAEmitterLayer layer];_caEmitterLayer.frame = self.view.frame;_caEmitterLayer.opaque = YES;[self.view.layer addSublayer:_caEmitterLayer];}// xxx@end

添加CAEmitterLayer到view.layer中:

CAEmitterLayer *emitter = [CAEmitterLayer layer];emitter.frame = self.bounds;[self.layer addSublayer:emitter];// 配置emitteremitter.renderMode = kCAEmitterLayerAdditive; // 粒子如何混合, 这里是直接重叠emitter.emitterPosition = position; // 发射点的位置

CAEmitterLayer其实是装载CAEmitterCell的容器, 有一个属性emitterCells, 将CAEmitterCell直接添加到该数组中, 即可实现粒子特效了.

CAEmitterCell

CAEmitterCell用来表示一个个的粒子, 它有一系列的参数用于设置效果.

// create a particle templateCAEmitterCell *cell = [[CAEmitterCell alloc] init];cell.contents = (__bridge id)[UIImage imageNamed:imageName].CGImage; // 粒子中的图片cell.yAcceleration = -10.f;// 粒子的初始加速度cell.xAcceleration = -110.f;cell.birthRate = 2.f; // 每秒生成粒子的个数cell.lifetime = 6.f; // 粒子存活时间cell.alphaSpeed = -0.3f; // 粒子消逝的速度cell.velocity = 30.f; // 粒子运动的速度均值cell.velocityRange = 30.f;// 粒子运动的速度扰动范围cell.emissionRange = M_PI * 10.f; // 粒子发射角度, 这里是一个扇形.// add particle template to emitteremitter.emitterCells = @[cell]; // 将粒子组成的数组赋值给CAEmitterLayer的emitterCells属性即可.

关于速度等属性, 可以设置一个均值和一个扰动范围:

Each layer has its own random number generator state. Emitter cell properties that are defined as a mean and a range, such as a cell’s speed, the value of the properties are uniformly distributed in the interval [M - R/2, M + R/2].

Demo

可参考Demo:

DemoCAEmitterLayer

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。