粒子效果動畫使用總結

伊凡19900發表於2018-01-04

我們常見的一些像下雪、下雨、火苗這類的動畫,都是可以使用粒子效果來實現。主要使用了類CAEmitterLayerCAEmitterCell來實現。下面我們將通過實現一個下雪的效果來說明該類的使用方法和各個屬性的含義。

CAEmitterLayer 可理解為粒子發射器

建立一個CAEmitterLayer的例項,也就是建立一個發射器。

CGRect rect = CGRectMake(0, 100, self.view.bounds.size.width, 50);
//建立發射器
CAEmitterLayer *emitter = [CAEmitterLayer layer];
emitter.frame = rect;
[self.view.layer addSublayer:emitter];
複製程式碼

設定發射器型別

//設定發射器型別
emitter.emitterShape = kCAEmitterLayerRectangle;
複製程式碼

這時候就要說一下屬性emitterShape的取值了。有6種取值kCAEmitterLayerPointkCAEmitterLayerLinekCAEmitterLayerRectanglekCAEmitterLayerCuboidkCAEmitterLayerCirclekCAEmitterLayerSphere。簡單介紹幾種

  • kCAEmitterLayerPoint 設定為該型別,發射器的所有粒子都將從一個相同的點建立。這個點是發射器的position。

粒子效果動畫使用總結

  • kCAEmitterLayerLine 設定為該值,所有粒子都將在發射器最上端的建立。

粒子效果動畫使用總結

  • kCAEmitterLayerRectangle 設定為該值,所有粒子都在發射器的整個區域建立。

粒子效果動畫使用總結

其他三種先不說了。 需要注意的,上述所說的區域不是emitterLayer的,而是由屬性emitterPositionemitterSize來確認的。 下面就來設定這兩個屬性的值,在該例子中,將其設定為和layer一樣了。

emitter.emitterPosition = CGPointMake(rect.size.width*0.5, rect.size.height*0.5);
emitter.emitterSize = rect.size;
複製程式碼

CAEmitterCell 可理解為我們要發射的例子

和我們之前說過的Animation一樣,CAEmitterCell也只不過是我們為你用來展現粒子形態的一個資料模型。

我們建立一個粒子,並且將圖片flake.png作為其內容。接下來發射器會建立他的很多各種各樣的拷貝來模擬真實的雪花。

CAEmitterCell *emitterCell = [CAEmitterCell emitterCell];
emitterCell.contents = (__bridge id _Nullable)([UIImage imageNamed:@"flake"].CGImage);
複製程式碼

接著新增程式碼

//設定粒子建立速率,也就是每秒產生的個數
emitterCell.birthRate = 20;
//設定粒子的生命週期,也就是在螢幕上存在的時間
emitterCell.lifetime = 3.5;
//將粒子賦給發射器
emitter.emitterCells = @[emitterCell];
複製程式碼

需要解釋的是emitterCells屬性。我們將emitterCells屬性設定為一個存放著CAEmitterCell型別資料的陣列。同一個發射器是可以發射不同型別的粒子的。

這回執行程式,我們將看到這樣的效果

粒子效果動畫使用總結

我們發現雖然產生了粒子,但是他們並不會運動。所以,繼續努力 新增程式碼

//設定粒子建立速率,也就是每秒產生的個數
emitterCell.birthRate = 200;
//設定粒子的生命週期,也就是在螢幕上存在的時間
emitterCell.lifetime = 3.5;
//設定粒子宣告週期範圍
emitterCell.lifetimeRange = 1.0;
//將粒子賦給發射器
emitter.emitterCells = @[emitterCell];
//設定y軸上的加速度
emitterCell.yAcceleration = 70.0f;
//設定x軸上的加速度
emitterCell.xAcceleration = 10.0f;
//設定粒子的初始速度
emitterCell.velocity = 20;
//設定粒子的初始角度 如果不設定這個值,我們發現粒子都是水平發射的
emitterCell.emissionLongitude = -M_PI_2;
//設定粒子的初始速度範圍 在此例子中範圍是 -180~220
emitterCell.velocityRange = 200.0f;
//設定粒子的初始角度範圍 此例子的範圍為 M_PI~0
emitterCell.emissionRange = M_PI_2;
//設定粒子的顏色
emitterCell.color = [UIColor colorWithRed:0.9 green:1.0 blue:1.0 alpha:1.0].CGColor;
//我們也可以設定隨機顏色,並且限定範圍。因為RGB的值最大為1.0,那Red來說,範圍並不會變為0.6~1.3,而是0.6~1.0。相似的,如果是負值,則最小為0
emitterCell.redRange = 0.3;
emitterCell.greenRange = 0.3;
emitterCell.blueRange = 0.3;

//設定粒子的大小及其大小範圍
emitterCell.scale = 0.8;
emitterCell.scaleRange = 0.8;

//設定讓粒子隨著時間推移每秒減小15%,如果設定為正值則每秒增加
emitterCell.scaleSpeed = -0.15;

//設定粒子透明度的變化範圍
emitterCell.alphaRange = 0.75;
//設定粒子變化速度
emitterCell.alphaSpeed = -0.15;
複製程式碼

好多屬性都是有range相關的型別,都是指定的範圍,沒有一個個的寫。 最終效果:

粒子效果動畫使用總結

github地址

相關文章