iOS 使用粒子效果实现点赞送礼物动画

效果.gif

代码

- (IBAction)likeAction:(id)sender {
    //初始化一个数组 用于装填模拟数据
    NSMutableArray *arr = [NSMutableArray array];
    //装填10个数据
    for (NSInteger i = 0; i < 10; i++) {
        //粒子初始化
        CAEmitterCell *cell = [CAEmitterCell emitterCell];
         //设置名字标识 最好不要重名 _beginI是一个全局变量
        _beginI++;
        NSString *cellName = [NSString stringWithFormat:@"cell_%d",_beginI];
        cell.name = cellName;
        //粒子产生率默认0
        cell.birthRate = 1;
         //透明度速度
        cell.alphaSpeed = 0.2;
        //透明度范围
        cell.alphaRange = 0.1;
        //生命周期
        cell.lifetime = 5;
        //生命周期范围 lifetime= lifetime(+/-) lifetimeRange
        cell.lifetimeRange = 1.5;
        //速度默认0 这里取随机数
        cell.velocity =  arc4random_uniform(100) + 100;
        //速度平均量
        cell.velocityRange = 80;
        //x y 三轴加速度分量默认0
        cell.yAcceleration = 10.f;
        //喷射角度方向 设置成向上
        cell.emissionLongitude = - M_PI_2;
        //发射角度范围,默认0,以扇形分布
        cell.emissionRange = M_PI_2/5;
        //缩放比例默认 1
        cell.scale = 0.3;
        //缩放速度
        cell.scaleRange = 0.1;
        // cell.color = UIColor.blueColor.CGColor; //颜色
        //设置单元内容 这里添加一张图片
        cell.contents = (id)[UIImage imageNamed:[NSString stringWithFormat:@"icon%u",arc4random_uniform(9)+1]].CGImage;
        //将模拟据打包
        [arr addObject:cell];
    }
    //将打包的数组装填
    [self.emitterCellArray addObject:arr];
    
    //_isFinalAnimation用于判断当前是否在做动画,如果没有在做动画则开始执行动画
    if (_isFinalAnimation) {
        _isFinalAnimation = NO;
       [self startAnimation];
    }
}
//开始动画
- (void)startAnimation{
    //设置粒子数组
    NSArray *emitterCells = self.emitterCellArray[0];
    self.emitterLayer.emitterCells = emitterCells;
    //5秒后停止当前动画效果
    [self performSelector:@selector(stopAnimation:) withObject:emitterCells afterDelay:5];
}
//停止动画
- (void)stopAnimation:(NSArray *)emitterCells{
    //根据cell标识将cell清零
    for (CAEmitterCell *cell in emitterCells) {
        [_emitterLayer setValue:@0 forKeyPath:[NSString stringWithFormat:@"emitterCells.%@.birthRate",cell.name]];
    }
    //移除当前动画数据组
    [self.emitterCellArray removeObjectAtIndex:0];
    if (self.emitterCellArray.count > 0) {
        //如果还有数据继续做动画
        [self startAnimation];
    }else{
        //没有数据 改变状态并移除全部动画
        _isFinalAnimation = YES;
        [self.emitterLayer removeAllAnimations];
    }
}

你可能感兴趣的:(iOS 使用粒子效果实现点赞送礼物动画)