IOS动画效果源代码整理(粒子、雪花、火焰、河流、蒸汽)

2020-01-21 04:42:57于海丽

学习神奇的粒子发射器,雪花纷纷落下的动画效果,就是通过CAEmitterLayer来实现的,这个layer还能创建火焰,河流,蒸汽的动画效果,常用于游戏开发。

Creating your emitter layer


let rect = CGRect(x: 0.0, y: -70.0, width: view.bounds.width, height: 50.0)
let emitter = CAEmitterLayer()
emitter.backgroundColor = UIColor.blueColor().CGColor
emitter.frame = rect
emitter.emitterShape = kCAEmitterLayerRectangle
view.layer.addSublayer(emitter)

代码创建了CAEmitterLayer,并设置了发射源形状emitterShape。

有几个常用的emitterShape:

kCAEmitterLayerPoint:使所有粒子在同一点创建发射器的位置。这是一个很好的选择用于火花或烟花,比如,你可以创建一个火花效应,通过创建所有的粒子在同一点上,使它们在不同的方向飞,然后消失。

kCAEmitterLayerLine:所有粒子沿发射架顶部的顶部。这是一个用于瀑布效应的发射极的形状;水粒子出现在瀑布的顶部边缘。

kCAEmitterLayerRectangle:创建粒子随机通过一个给定的矩形区域。

Adding an emitter frame

前面是设置了layer Frame,下面设置layer里面的Emitter的frame


emitter.emitterPosition = CGPoint(x: rect.width * 0.5, y: rect.height * 0.5)
emitter.emitterSize = rect.size

代码设置了Emitter中心点是layer的中心点,size和layer一样。

[]Creating an emitter cell

现在,您已经配置了发射器的位置和大小,可以继续添加Cell。 Cell是表示一个粒子源的数据模型。是CAEmitterLayer一个单独的类,因为一个发射器可以包含一个或多个粒子。 例如,在一个爆米花动画,你可以有三种不同的细胞代表一个爆米花的不同状态:完全炸开,一半炸开和没有炸开:


let emitterCell = CAEmitterCell()
emitterCell.contents = UIImage(named: "flake.png")!.CGImage
emitterCell.birthRate = 20 
emitterCell.lifetime = 3.5 
emitter.emitterCells = [emitterCell]

代码每一秒创建20个cell,每个cell有3.5s的生命周期,之后一些cell就会消失

[]Controlling your particles

上面设置的cell不会动,需要给它个加速度


emitterCell.xAcceleration = 10.0
emitterCell.yAcceleration = 70.0

设置Cell在X轴,Y轴的加速度。


emitterCell.velocity = 20.0 
// x-y平面的发射方向
// -M_PI_2 垂直向上
emitterCell.emissionLongitude = CGFloat(-M_PI_2)

设置起始速度,发射的方向是通过emissionLongitude属性定义的。

[]Adding randomness to your particles


emitterCell.velocityRange = 200.0

设置其实速度的随机范围,每个粒子的速度将是一个随机值之间(20-200)= 180 ~(20 + 200)= 220。负初始速度的粒子不会向上飞,一旦出现在屏幕上,他们就会开始浮动。带正速度的粒子先飞起来,然后再浮。