Ios 动画层

Ios 动画层,ios,iphone,objective-c,core-animation,cashapelayer,Ios,Iphone,Objective C,Core Animation,Cashapelayer,我用以下代码绘制了一个图表: CAShapeLayer *curentGraph = [CAShapeLayer new]; CGMutablePathRef linePath = CGPathCreateMutable(); curentGraph.lineWidth = 3.0f; curentGraph.fillColor = [[UIColor clearColor] CGColor]; curentGraph.strokeColor = [colorGraph CGColor]; fo

我用以下代码绘制了一个图表:

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
。就像他们在中国一样


如何像那样设置图形的动画?

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

下面是一个
CAShapeLayer
子类,它允许您隐式地设置其
路径的动画(无需声明
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
@implementation CAShapeLayerAnim
-(id)actionForKey:(NSString*)事件{
if([事件isEqualToString:@“路径”]){
CABasicAnimation*动画=[CABasicAnimation]
animationWithKeyPath:event];
animation.duration=[CATransaction animationDuration];
animation.timingFunction=[CATTransaction
动画计时功能];
返回动画;
}
return[super-actionForKey:event];
}
@结束

对于动画,您需要使用CAShapeLayer的
strokeStart
strokeEnd
属性

请参见中的示例
CAShapeLayer
动画

从文档
strokeStart

此属性的值必须在0.0到1.0之间。此属性的默认值为1.0

与strokeEnd属性相结合,该属性定义笔划路径的子区域。此属性中的值表示沿路径开始笔划的相对点,而strokeEnd属性定义终点。值0.0表示路径的开始,值1.0表示路径的结束。中间的值沿路径长度线性解释


不需要创建CAShapeLayer的自定义子类。默认情况下,CAShapeLayer已经对其路径执行隐式动画。@Duncac仔细检查文档中路径属性的“讨论”:“与大多数可设置动画的属性不同,路径(与所有CGPathRef可设置动画的属性一样)不支持隐式动画。”也就是说,这可能是有原因的。我不确定我是否会创建子类只是为了添加对隐式路径动画的支持。@DavidRönnqvist,哦,我的错误。你说得对(像往常一样)对不起,西里尔。这也是我的第一反应。当我去文档中查找要在我的评论中使用的引用时,我看到/记住了它;)