路径动画

自定义view

-懒加载路径

@property (nonatomic, strong) UIBezierPath * path;
- (UIBezierPath *)path
{
    if (_path == nil) {
        _path = [UIBezierPath bezierPath];
        _path.lineWidth = 10;
    }
    return _path;
}

-触摸方法

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch * touch = [touches anyObject];
    
    //获取手指的触摸点
    CGPoint curP = [touch locationInView:self];
    
    [self.path moveToPoint:curP];
    
    [self setNeedsDisplay];
    
}

-移动手指把路径添加到path中

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch * touch = [touches anyObject];
    
    //获取手指的触摸点
    CGPoint curP = [touch locationInView:self];
    
    [self.path addLineToPoint:curP];
    
    [self setNeedsDisplay];
}

-开始绘制

- (void)drawRect:(CGRect)rect
{
    [self.path stroke];
}

-开始动画点击

- (void)startAnima
{
    //跟随路径动画
    //图层
    CAShapeLayer * layer = [CAShapeLayer layer];
    
    layer.path = self.path.CGPath;
    
    layer.lineWidth = 10;
    
    layer.fillColor = [UIColor whiteColor].CGColor;
    
    layer.strokeColor = [UIColor redColor].CGColor;
    
    
    [self.layer addSublayer:layer];
    
    CABasicAnimation * anima = [CABasicAnimation animation];
    
    anima.keyPath = @"strokeEnd";
    anima.fromValue = @0;
    anima.toValue = @1;
    anima.duration = 5;
    
    [layer addAnimation:anima forKey:nil];
    
    //清空划线
    [self.path removeAllPoints];
    
}

你可能感兴趣的:(路径动画)