首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动画CAShapeLayer

动画CAShapeLayer
EN

Stack Overflow用户
提问于 2014-02-14 21:32:34
回答 3查看 8.4K关注 0票数 2

我用下面的代码画了一张图:

代码语言:javascript
复制
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中做的那样。

我如何让我的图表像那样动画化呢?

EN

回答 3

Stack Overflow用户

发布于 2014-02-14 21:59:04

CAShapeLayer上的path属性是可设置动画的。这意味着您可以创建一条路径,其中每个y值都是0.0,并且从该路径到真实图形的动画。只需确保路径的点数相同即可。这应该很简单,因为您已经有了循环。

代码语言:javascript
复制
CGMutablePathRef startPath = CGPathCreateMutable();
for (NSValue *value in arrOfPoints) {
    CGPoint pt = [value CGPointValue];
    CGPathAddLineToPoint(startPath, NULL, pt.x, 0.0);
}

然后,可以通过为@"path"关键点创建CABasicAnimation来设置路径动画。

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2014-02-14 22:03:53

下面是一个CAShapeLayer子类,它允许您隐式地对其path进行动画处理(而不必声明CABasicAnimation):

接口:

代码语言:javascript
复制
@interface CAShapeLayerAnim : CAShapeLayer
@end

实施:

代码语言:javascript
复制
@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
票数 7
EN

Stack Overflow用户

发布于 2014-05-03 23:14:23

对于动画,您需要使用CAShapeLayer的strokeStartstrokeEnd属性。

请参见Ole Begemann blog post中的示例CAShapeLayer动画。

来自documentation strokeStart

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

与strokeEnd属性结合使用时,此属性定义要描边的路径的子区域。此属性中的值指示沿路径开始描边的相对点,而strokeEnd属性定义结束点。值0.0表示路径的开始,而值1.0表示路径的结束。介于两者之间的值沿路径长度线性解释。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21780769

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档