新建一个 xcode 项目,然后在 ViewController.m 编写代码实现效果。
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//1. 设置CAEmitterLayer
CAEmitterLayer * emitterLayer = [CAEmitterLayer layer];
//2.在背景图上添加粒子图层
[self.view.layer addSublayer:emitterLayer];
//3.发射形状--线性
emitterLayer.emitterShape = kCAEmitterLayerLine;
emitterLayer.emitterMode = kCAEmitterLayerSurface;
emitterLayer.emitterSize = self.view.frame.size;
emitterLayer.emitterPosition = CGPointMake(self.view.frame.size.width * 0.5, -10);
//2. 配置cell
CAEmitterCell * emitterCell = [CAEmitterCell emitterCell];
emitterCell.contents = (id)[UIImage imageNamed:@"hongbao"].CGImage;
emitterCell.birthRate = 1.0f;
emitterCell.lifetime = 30.0f;
emitterCell.speed = 2.0f;
emitterCell.velocity = 10.0f;
emitterCell.velocityRange = 10.0f;
emitterCell.yAcceleration = 60.0f;
emitterCell.scale = 0.05f;
emitterCell.scaleRange = 0.0f;
emitterLayer.emitterCells = @[emitterCell];
}
@end
运行效果如下: