iOS开发核心动画之粒子效果
一. 示意图
绘画出一条线,点击开始有很多粒子绕着线运动,点击重绘消除粒子和线

二. 实现代码
设计思路:自定义一个View来描述控制器的View,在View加载过程中进行初始化,给View添加手势(UIPanGestureRecognizer),将自定义View转成复制层,创建一个粒子层,添加到复制层上,并保存粒子
监听滑动手势,记录起始点,移动过程中添加直线并重绘
三. 代码实现
1. 自定义View来描述控制器View,将控制器View转为复制层
+ (Class)layerClass{return [CAReplicatorLayer class];}
2. 在加载控制器View初始化
初始化过程中创建滑动手势/创建复制层和粒子层
设置复制层相关属性:赋值个数/动画延迟时间
- (void)awakeFromNib{[self setup];}- (void)setup{// 1.创建手势UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];// 2.添加手势[self addGestureRecognizer:pan];// 3.创建粒子复制层CAReplicatorLayer *copyLayer = (CAReplicatorLayer *)self.layer;copyLayer.instanceCount = 30;copyLayer.instanceDelay = 0.25;CALayer *layer = [[CALayer alloc] init];layer.frame = CGRectMake(-10, 0, 10, 10);layer.backgroundColor = [UIColor redColor].CGColor;[copyLayer addSublayer:layer];self.dotlayer = layer;}
3. 将创建出来的粒子保存,设置一个UIBezierPater属性
/** 路径 */@property (nonatomic, strong) UIBezierPath *path;/** 粒子 */@property (nonatomic, weak) CALayer *dotlayer;
4. 监听手势进行绘线
// 监听手势- (void)pan:(UIPanGestureRecognizer *)pan{// 获取当前点CGPoint curP = [pan locationInView:self];if (pan.state == UIGestureRecognizerStateBegan) { // 开始滑动// 绘制起始点[self.path moveToPoint:curP];} else if (pan.state == UIGestureRecognizerStateChanged) {// 添加直线[self.path addLineToPoint:curP];// 重绘[self setNeedsDisplay];}}
5. UIBezierPater路径懒加载
// 路径懒加载- (UIBezierPath *)path{if (!_path) {UIBezierPath *path = [UIBezierPath bezierPath];_path = path;}return _path;}
6. 绘制
// 绘制- (void)drawRect:(CGRect)rect {[self.path stroke];}
7. 线绘制完后点击开始,创建帧动画
- (IBAction)start {// 1.创建帧动画CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];anim.keyPath = @"position";anim.path = self.path.CGPath;anim.repeatCount = MAXFLOAT;anim.duration = 3;[self.dotlayer addAnimation:anim forKey:nil];}
8. 点击重绘
- (IBAction)redraw {// 删除所有动画[self.dotlayer removeAllAnimations];// 销毁路径[self.path removeAllPoints];// 重绘[self setNeedsDisplay];}

浙公网安备 33010602011771号