我用以下代码绘制图形:

CAShapeLayer *curentGraph = [CAShapeLayer new];
CGMutablePathRef linePath = CGPathCreateMutable();
curentGraph.lineWidth = 3.0f;
curentGraph.fillColor = [[UIColor clearColor] CGColor];
curentGraph.strokeColor = [colorGraph CGColor];
for (NSValue *value in arrOfPoints) {
    CGPoint pt = [value CGPointValue];
    CGPathAddLineToPoint(linePath, NULL, pt.x,pt.y);
};
curentGraph.path = linePath;CGPathRelease(linePath);
[self.layer addSublayer:curentGraph];

它看起来像这样

但是我有一个问题。我需要为图表显示动画。每个点应从位置y = 0移到y = pt.y。就像他们在the graph on this site中所做的一样。

我该如何为我的图制作动画?

最佳答案

这是一个CAShapeLayer子类,可让您隐式为其path设置动画(而无需声明CABasicAnimation):

接口:

@interface CAShapeLayerAnim : CAShapeLayer
@end

实现方式:
@implementation CAShapeLayerAnim

- (id<CAAction>)actionForKey:(NSString *)event {
    if ([event isEqualToString:@"path"]) {
        CABasicAnimation *animation = [CABasicAnimation
            animationWithKeyPath:event];
        animation.duration = [CATransaction animationDuration];
        animation.timingFunction = [CATransaction
            animationTimingFunction];
        return animation;
    }
   return [super actionForKey:event];
}

@end

08-19 08:01