Search code examples
objective-cuibezierpathcgpointuianimationcashapelayer

How to animate a drawn line in Objective C?


I am trying to animate drawn objects, for example I have drawn a line with this approach:

    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(Center.x, Center.y)];
    [path addLineToPoint:CGPointMake(Point.x,Point.y)];

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [path CGPath];
    shapeLayer.strokeColor = [[UIColor whiteColor] CGColor];
    shapeLayer.lineWidth = 1.5;
    shapeLayer.fillColor = [[UIColor clearColor] CGColor];

    [self.view.layer addSublayer:shapeLayer];

After a while I need to animate the line to have a different Point, but keeping Center as is, but I have no idea how to do that. Is my approach alright? Is there a better way to do so?


Solution

  • Solved it:

        CABasicAnimation *morph = [CABasicAnimation animationWithKeyPath:@"path"];
        morph.duration = 1.0;
        UIBezierPath *path5 = [UIBezierPath bezierPath];
        [path5 moveToPoint:CGPointMake(P22.x+5, P22.y+5)];
        [path5 addLineToPoint:CGPointMake(P21.x,P21.y)];
        morph.fromValue = (id) path.CGPath;
        morph.toValue = (id) path5.CGPath;
    
        [shapeLayer addAnimation:morph forKey:nil];
    
        //next line to update the shapeLayer's new path
        shapeLayer.path = path5.CGPath;