IOS动画效果源代码整理(粒子、雪花、火焰、河流、蒸汽)
学习神奇的粒子发射器,雪花纷纷落下的动画效果,就是通过CAEmitterLayer来实现的,这个layer还能创建火焰,河流,蒸汽的动画效果,常用于游戏开发。
Creatingyouremitterlayer
letrect=CGRect(x:0.0,y:-70.0,width:view.bounds.width,height:50.0) letemitter=CAEmitterLayer() emitter.backgroundColor=UIColor.blueColor().CGColor emitter.frame=rect emitter.emitterShape=kCAEmitterLayerRectangle view.layer.addSublayer(emitter)
代码创建了CAEmitterLayer,并设置了发射源形状emitterShape。
有几个常用的emitterShape:
kCAEmitterLayerPoint:使所有粒子在同一点创建发射器的位置。这是一个很好的选择用于火花或烟花,比如,你可以创建一个火花效应,通过创建所有的粒子在同一点上,使它们在不同的方向飞,然后消失。
kCAEmitterLayerLine:所有粒子沿发射架顶部的顶部。这是一个用于瀑布效应的发射极的形状;水粒子出现在瀑布的顶部边缘。
kCAEmitterLayerRectangle:创建粒子随机通过一个给定的矩形区域。
Addinganemitterframe
前面是设置了layerFrame,下面设置layer里面的Emitter的frame
emitter.emitterPosition=CGPoint(x:rect.width*0.5,y:rect.height*0.5) emitter.emitterSize=rect.size
代码设置了Emitter中心点是layer的中心点,size和layer一样。
[]Creatinganemittercell
现在,您已经配置了发射器的位置和大小,可以继续添加Cell。Cell是表示一个粒子源的数据模型。是CAEmitterLayer一个单独的类,因为一个发射器可以包含一个或多个粒子。例如,在一个爆米花动画,你可以有三种不同的细胞代表一个爆米花的不同状态:完全炸开,一半炸开和没有炸开:
letemitterCell=CAEmitterCell() emitterCell.contents=UIImage(named:"flake.png")!.CGImage emitterCell.birthRate=20 emitterCell.lifetime=3.5 emitter.emitterCells=[emitterCell]
代码每一秒创建20个cell,每个cell有3.5s的生命周期,之后一些cell就会消失
[]Controllingyourparticles
上面设置的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属性定义的。
[]Addingrandomnesstoyourparticles
emitterCell.velocityRange=200.0
设置其实速度的随机范围,每个粒子的速度将是一个随机值之间(20-200)=180~(20+200)=220。负初始速度的粒子不会向上飞,一旦出现在屏幕上,他们就会开始浮动。带正速度的粒子先飞起来,然后再浮。
emitterCell.emissionRange=CGFloat(M_PI_2)
原来,你配置的所有粒子射直线上升(π/2角)作为他们的出现。上面这行代码表示为每个粒子随机选一个发射角度在(-π/2+π/2)=180度(-π/2+π/2)=0度之间。
[]Changingparticlecolor
设置你的粒子颜色
emitterCell.color=UIColor(red:0.9,green:1.0,blue:1.0,alpha:1.0).CGColor
还可以设置粒子的颜色RGB范围:
emitterCell.redRange=0.1 emitterCell.greenRange=0.1 emitterCell.blueRange=0.1
由于RGB最大为1.0,所以red是取值0.81.0,green:0.91.0,blue:0.9~1.0
[]Randomizingparticleappearance
之前的粒子都是一样大的,这里给粒子分配一个随机大小。
emitterCell.scale=0.8 emitterCell.scaleRange=0.8
设置粒子是原来的80%大小,随机范围是从0.0到1.6。
emitterCell.scaleSpeed=-0.15
粒子每秒钟按15%的体积缩小。
还可以设置透明度
emitterCell.alphaRange=0.75 emitterCell.alphaSpeed=-0.15
透明度0.25~1.0,每秒透明度减少15%。