画线动画、平滑过渡曲线

通过UIBezierPath来动画画线,以及平滑地画线

Posted by Ted on January 15, 2017

一、动画画线

1、创建CAShaperLayer

    //创建出CAShapeLayer
    _shapeLayer = [CAShapeLayer layer];
    _shapeLayer.frame = self.view.bounds;//设置shapeLayer的尺寸和位置
    _shapeLayer.position = self.view.center;
    _shapeLayer.fillColor = [UIColor clearColor].CGColor;//填充颜色为ClearColor

2、定义线条

    //设置线条的宽度和颜色
    _shapeLayer.lineWidth = 1.0f;
    _shapeLayer.strokeColor = [UIColor redColor].CGColor;

3、设置线条路径

    CGPoint point_1 = CGPointMake(100, 100);
    CGPoint point_2 = CGPointMake(120, 150);
    CGPoint point_3 = CGPointMake(200, 200);
    NSMutableArray *array = [NSMutableArray arrayWithObjects:@(point_1),@(point_2),@(point_3), nil];
    UIBezierPath *path = [[UIBezierPath alloc] init];
    [path moveToPoint:[[array firstObject] CGPointValue]];
    
    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, [array count] - 1)];
    [array enumerateObjectsAtIndexes:indexSet
                                      options:0
                                   usingBlock:^(NSValue *pointValue, NSUInteger idx, BOOL *stop) {
                                       [path addLineToPoint:[pointValue CGPointValue]];
                                   }];
    path.usesEvenOddFillRule = YES;

4、添加动画

    //创建动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:NSStringFromSelector(@selector(strokeEnd))];
    animation.fromValue = @0.0;
    animation.toValue = @1.0;
    animation.duration = 2;//动画时间;
    [_shapeLayer addAnimation:animation forKey:NSStringFromSelector(@selector(strokeEnd))];

5、效果

img

二、平滑曲线

    UIBezierPath* aPath = [UIBezierPath bezierPath];
    aPath.lineWidth = 5.0;
    aPath.lineCapStyle = kCGLineCapRound; //线条拐角
    aPath.lineJoinStyle = kCGLineCapRound; //终点处理
    [aPath moveToPoint:CGPointMake(20, 50)];
    [aPath addCurveToPoint:CGPointMake(200, 50) controlPoint1:CGPointMake(110, 0) controlPoint2:CGPointMake(110, 100)];

img

https://github.com/helloted/Demo_for_WebSite/tree/master/DrawLineDemo