Search code examples
iphoneobjective-cioscalayerquartz-2d

Animating the drawing of a line


I'm trying to animate the drawing of a line by the following way:

.h

CAShapeLayer *rootLayer;
CAShapeLayer *lineLayer;
CGMutablePathRef path;

.m

 path = CGPathCreateMutable();
 CGPathMoveToPoint(path, nil, self.frame.size.width/2-100, 260);
 CGPathAddLineToPoint(path, nil, self.frame.size.width/2+100.0, 260);    
 CGPathCloseSubpath(path);

 self.rootLayer = [CALayer layer];
 rootLayer.frame = self.bounds;
[self.layer addSublayer:rootLayer];

 self.lineLayer = [CAShapeLayer layer];
[lineLayer setPath:path];
[lineLayer setFillColor:[UIColor redColor].CGColor];
[lineLayer setStrokeColor:[UIColor blueColor].CGColor];
[lineLayer setLineWidth:1.5];
[lineLayer setFillRule:kCAFillRuleNonZero];
[rootLayer addSublayer:lineLayer];

[self performSelector:@selector(startTotalLine) withObject:nil afterDelay:1.5];

- (void)startTotalLine
{    
      CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"animatePath"];
      [animation setDuration:3.5];
       animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
      [animation setAutoreverses:NO];
      [animation setFromValue:(id)path];
      [animation setToValue:(id)path];
      [lineLayer addAnimation:animation forKey:@"animatePath"];    
}

The line had drawn before the startTotalLine method is invoked. Also, the startTotalLine method doesn't affect the line.

I want it to animate the the line drawing from right to left.


Solution

  • I think the easiest way to do what you want, is to present some UIView that is 1.5 pixel height and animate it's width. Ask me if I'm not clear.

    I think your code doesn't work because your variable path is not a layer property. Read manuals:

    CABasicAnimation provides basic, single-keyframe animation capabilities for a layer property.

    And you do something strange here:

    [animation setFromValue:(id)path];
    [animation setToValue:(id)path];
    

    EDIT: I stumbled upon an article, and understood what you were try to achieve! Now I think the reason you failed is that you can animate path that doesn't change number of points. And now I thought you can create a path-line with two points. At first they are at same place and another path is the line you want to end up with. Now animate from first path to the second. I think it should work, but I'm not sure.

    EDIT: Definitely! You need this guy's code. Git link.