I am new to using Quartz2D, and to start small I wanted to draw a line, but have that line be animated from start to finish. From the blogs I have read and similar questions I have looked at, it seems I need to set a path for layer, and animate on that layer. The problem for me is, even though a layer has a path property, I am unsure how to go about properly settings up a path for it.
I have a UIView displaying, and it shows a line just fine if I comment out the animation code.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGFloat components[] = {0.0, 0.0, 1.0, 1.0};
CGColorRef color = CGColorCreate(colorspace, components);
CGContextSetStrokeColorWithColor(context, color);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, 300, 400);
CGContextStrokePath(context);
CGColorSpaceRelease(colorspace);
CGColorRelease(color);
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = 10.0;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
//[aLayer addAnimation:pathAnimation forKey:@"strokeEndAnimation"];
What do I need to do to animate a line from start to finish?
Here is what I've used to animate a line being drawn, make sure to import Quartz of course:
//Create the bezier path that will hold all the points of data
UIBezierPath* bezierPath = [UIBezierPath bezierPath];
[[UIColor greenColor] setFill];
[bezierPath fill];
[[UIColor redColor] setStroke];
[bezierPath stroke];
for (int i = 10 ; i < 20; i++) {
//If its the first point we need to make sure and move to that point not add to it
if (i == 10)
[bezierPath moveToPoint: CGPointMake(10, 10)];
else
[bezierPath addLineToPoint: CGPointMake(i * 2, i * 3)];
}
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.strokeColor = [[UIColor blueColor] CGColor];
shapeLayer.fillColor = nil;
shapeLayer.lineWidth = 10.0f;
shapeLayer.lineJoin = kCALineJoinRound;
shapeLayer.path = bezierPath.CGPath;
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = 10.0;
pathAnimation.fromValue = @(0.0f);
pathAnimation.toValue = @(1.0f);
[shapeLayer addAnimation:pathAnimation forKey:@"strokeEnd"];
[self.view.layer addSublayer:shapeLayer];