我用下面的代码画了一张图:
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中做的那样。
我如何让我的图表像那样动画化呢?
发布于 2014-02-14 21:59:04
CAShapeLayer上的path属性是可设置动画的。这意味着您可以创建一条路径,其中每个y值都是0.0,并且从该路径到真实图形的动画。只需确保路径的点数相同即可。这应该很简单,因为您已经有了循环。
CGMutablePathRef startPath = CGPathCreateMutable();
for (NSValue *value in arrOfPoints) {
CGPoint pt = [value CGPointValue];
CGPathAddLineToPoint(startPath, NULL, pt.x, 0.0);
}然后,可以通过为@"path"关键点创建CABasicAnimation来设置路径动画。
CABasicAnimation *pathAppear = [CABasicAnimation animationWithKeyPath:@"path"];
pathAppear.duration = 2.0; // 2 seconds
pathAppear.fromValue = (__bridge id)startPath;
pathAppear.toValue = (__bridge id)linePath;
[yourShapeLayer addAnimation:pathAppear forKey:@"make the path appear"];发布于 2014-02-14 22:03:53
下面是一个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发布于 2014-05-03 23:14:23
对于动画,您需要使用CAShapeLayer的strokeStart和strokeEnd属性。
请参见Ole Begemann blog post中的示例CAShapeLayer动画。
来自documentation strokeStart
此属性的值必须在0.0到1.0的范围内。此属性的默认值为1.0。
与strokeEnd属性结合使用时,此属性定义要描边的路径的子区域。此属性中的值指示沿路径开始描边的相对点,而strokeEnd属性定义结束点。值0.0表示路径的开始,而值1.0表示路径的结束。介于两者之间的值沿路径长度线性解释。
https://stackoverflow.com/questions/21780769
复制相似问题