iOS开发核心动画之粒子效果

一. 示意图

    绘画出一条线,点击开始有很多粒子绕着线运动,点击重绘消除粒子和线


二. 实现代码

    设计思路:自定义一个View来描述控制器的View,在View加载过程中进行初始化,给View添加手势(UIPanGestureRecognizer),将自定义View转成复制层,创建一个粒子层,添加到复制层上,并保存粒子

    监听滑动手势,记录起始点,移动过程中添加直线并重绘


三. 代码实现

1. 自定义View来描述控制器View,将控制器View转为复制层

  1. + (Class)layerClass
  2. {
  3. return [CAReplicatorLayer class];
  4. }

2. 在加载控制器View初始化

初始化过程中创建滑动手势/创建复制层和粒子层

设置复制层相关属性:赋值个数/动画延迟时间

  1. - (void)awakeFromNib
  2. {
  3. [self setup];
  4. }
  5. - (void)setup
  6. {
  7. // 1.创建手势
  8. UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
  9. // 2.添加手势
  10. [self addGestureRecognizer:pan];
  11. // 3.创建粒子复制层
  12. CAReplicatorLayer *copyLayer = (CAReplicatorLayer *)self.layer;
  13. copyLayer.instanceCount = 30;
  14. copyLayer.instanceDelay = 0.25;
  15. CALayer *layer = [[CALayer alloc] init];
  16. layer.frame = CGRectMake(-10, 0, 10, 10);
  17. layer.backgroundColor = [UIColor redColor].CGColor;
  18. [copyLayer addSublayer:layer];
  19. self.dotlayer = layer;
  20. }

3. 将创建出来的粒子保存,设置一个UIBezierPater属性

  1. /** 路径 */
  2. @property (nonatomic, strong) UIBezierPath *path;
  3. /** 粒子 */
  4. @property (nonatomic, weak) CALayer *dotlayer;
4. 监听手势进行绘线
  1. // 监听手势
  2. - (void)pan:(UIPanGestureRecognizer *)pan
  3. {
  4. // 获取当前点
  5. CGPoint curP = [pan locationInView:self];
  6. if (pan.state == UIGestureRecognizerStateBegan) { // 开始滑动
  7. // 绘制起始点
  8. [self.path moveToPoint:curP];
  9. } else if (pan.state == UIGestureRecognizerStateChanged) {
  10. // 添加直线
  11. [self.path addLineToPoint:curP];
  12. // 重绘
  13. [self setNeedsDisplay];
  14. }
  15. }

5. UIBezierPater路径懒加载 

  1. // 路径懒加载
  2. - (UIBezierPath *)path
  3. {
  4. if (!_path) {
  5. UIBezierPath *path = [UIBezierPath bezierPath];
  6. _path = path;
  7. }
  8. return _path;
  9. }

6. 绘制

  1. // 绘制
  2. - (void)drawRect:(CGRect)rect {
  3. [self.path stroke];
  4. }

7. 线绘制完后点击开始,创建帧动画

  1. - (IBAction)start {
  2. // 1.创建帧动画
  3. CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
  4. anim.keyPath = @"position";
  5. anim.path = self.path.CGPath;
  6. anim.repeatCount = MAXFLOAT;
  7. anim.duration = 3;
  8. [self.dotlayer addAnimation:anim forKey:nil];
  9. }


8. 点击重绘

  1. - (IBAction)redraw {
  2. // 删除所有动画
  3. [self.dotlayer removeAllAnimations];
  4. // 销毁路径
  5. [self.path removeAllPoints];
  6. // 重绘
  7. [self setNeedsDisplay];
  8. }


posted @ 2015-11-27 13:02  文刂Rn  阅读(777)  评论(0编辑  收藏  举报