动画CAShapeLayer

3

我用这段代码画了一个图表:

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

并且它长这样

graph截图

但我有一个问题。我需要在图形出现时对其进行动画处理。每个点都应该从位置 y = 0 向上移动到 y = pt.y 的位置。就像此网站上的图表一样。

我如何才能像那样动画显示我的图形呢?

3个回答

7

CAShapeLayer上的path属性是可动画的。这意味着您可以创建一个路径,其中每个y值都为0.0,然后从该路径动画到实际图形。只需确保路径具有相同数量的点即可。由于您已经有了循环,所以这应该很容易。

CGMutablePathRef startPath = CGPathCreateMutable();
for (NSValue *value in arrOfPoints) {
    CGPoint pt = [value CGPointValue];
    CGPathAddLineToPoint(startPath, NULL, pt.x, 0.0);
}

接下来,您可以通过创建一个CABasicAnimation针对@"path"键来动画路径。

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

7
这里有一个 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

不需要创建CAShapeLayer的自定义子类。CAShapeLayer默认已经对其路径进行了隐式动画。 - Duncan C
2
@DuncanC请仔细查看文档中“路径属性”的“讨论”部分:“与大多数可动画属性不同,路径(以及所有CGPathRef可动画属性)不支持隐式动画。” - David Rönnqvist
1
话虽如此,也许有其原因。我不确定是否应该子类化只是为了添加对隐式路径动画的支持。 - David Rönnqvist
@DavidRönnqvist,糟糕,我的错误。你是对的(像往常一样)。抱歉Cyrille。 - Duncan C
这也是我的第一反应。当我去文档中寻找引用以在我的评论中使用时,我看到/记起了它 ;) - David Rönnqvist
如果你只打算对一个实例进行子类化,那么这并不总是值得的,但是这个实例恰好来自我的工具箱库。 - Cyrille

2
对于动画,您需要使用CAShapeLayer的strokeStartstrokeEnd属性。
Ole Begemann博客文章中查看CAShapeLayer动画示例。
从文档中可以看到strokeStart的定义:

该属性的值必须在0.0到1.0的范围内。该属性的默认值为1.0。

结合strokeEnd属性,该属性定义要描边的路径的子区域。该属性中的值表示沿路径开始描边的相对点,而strokeEnd属性则定义了结束点。值为0.0表示路径的开始,而值为1.0表示路径的结束。中间的值沿路径长度线性解释。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接