CAEmitterLayer和CAEmitterCell的基本用法

對於iOS的動畫,大多數人都能掌握UIViewAnimation和CoreAnimation的知識,用來實現基本的動畫都夠用了,但有些常見的動畫仍是難以用這些知識去實現,例如 火焰、煙霧、下雨、下雪等。
因而瞭解到 iOS 系統的CoreGraphic框架能夠簡單的實現粒子系統的效果, 實現粒子系統主要用到兩個類CAEmitterLayer和CAEmitterCell 。

1、 如下對着兩個類作個簡單的介紹:數組

一、CAEmitterLayer。 這個主要是定義粒子原型發射層的形狀和發射位置,發射源的尺寸以及發射的模式等。框架

二、CAEmitterCell 單個粒子的原型,一般有多個,根據cell的屬性和CAEmitterCell的配置,由uikit隨機生成,粒子原型的屬性包括粒子的圖片,顏色,方向,運動,縮放比例和生命週期等。動畫

這兩個類的參數看起來彷佛很簡單,但這些參數的不一樣組合配合上相對應圖片,則能夠實現許多意想不到的動畫效果。ui

2、下面咱們經過一個簡單的demo來初步認識一下這兩個類的基礎用法spa

#import "ViewController.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setEmitter];
}

- (void)setEmitter{
    //添加背景圖
    UIImage *bgImage = [UIImage imageNamed:@"bg.jpeg"];
    self.view.backgroundColor = [UIColor     colorWithPatternImage:bgImage];

    //粒子圖層
    CAEmitterLayer *snowLayer = [CAEmitterLayer layer];
    snowLayer.backgroundColor = [UIColor redColor].CGColor;
    //發射位置
    snowLayer.emitterPosition = CGPointMake(0, 0);
    //發射源的尺寸
    snowLayer.emitterSize = CGSizeMake(640, 1);
    //發射源的形狀
    snowLayer.emitterMode = kCAEmitterLayerSurface;
    //發射模式
    snowLayer.emitterShape = kCAEmitterLayerLine;
    
    //存放粒子種類的數組
    NSMutableArray *snow_array = @[].mutableCopy;
    
    for (NSInteger i=1; i<5; i++) {
        //snow
        CAEmitterCell *snowCell = [CAEmitterCell emitterCell];
        snowCell.name = @"snow";
        //產生頻率
        snowCell.birthRate = 15.0f;
        //生命週期
        snowCell.lifetime = 30.0f;
        //運動速度
        snowCell.velocity = 1.0f;
        //運動速度的浮動值
        snowCell.velocityRange = 10;
        //y方向的加速度
        snowCell.yAcceleration = 2;
        //拋灑角度的浮動值
        snowCell.emissionRange = 0.5*M_PI;
        //自旋轉角度範圍
        snowCell.spinRange = 0.25*M_PI;
        //粒子透明度在生命週期內的改變速度
        snowCell.alphaSpeed = 2.0f;
        //cell的內容,通常是圖片
        NSString *snow_str = [NSString stringWithFormat:@"snow%ld",i];
        snowCell.contents = (id)[UIImage imageNamed:snow_str].CGImage;
        
        [snow_array addObject:snowCell];
    }

    //添加到當前的layer上
    snowLayer.shadowColor = [[UIColor redColor]CGColor];
    snowLayer.cornerRadius = 1.0f;
    snowLayer.shadowOffset = CGSizeMake(1, 1);
    snowLayer.emitterCells = [NSArray arrayWithArray:snow_array];
    [self.view.layer insertSublayer:snowLayer atIndex:0];
}

@end

效果以下圖所示:code

clipboard.png

這是一個最簡單的粒子效果的實現了,對於想實現其餘的效果,只需對參數進行設置不一樣參數間的搭配可以實現咱們大部分粒子系統的效果。爲此必須詳細掌握每一個參數的用處,這裏便很少贅述。orm

相關文章
相關標籤/搜索