0

我是使用 Quartz2D 的新手,从小处着手,我想画一条线,但要让这条线从头到尾进行动画处理。从我读过的博客和我看过的类似问题来看,似乎我需要为图层设置路径,并在该图层上设置动画。对我来说问题是,即使图层具有路径属性,我也不确定如何正确设置路径。

我有一个 UIView 显示,如果我注释掉动画代码,它会显示一行就好了。

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"];

我需要做什么才能从头到尾为一条线设置动画?

4

1 回答 1

0

这是我用来绘制线条的动画,当然要确保导入 Quartz:

//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];
于 2013-07-15T23:37:40.683 回答