Animation CAShapeLayer

て烟熏妆下的殇ゞ 提交于 2019-12-04 15:59:10

Here is a CAShapeLayer subclass that'll allow you to animate its path implicitly (without having to declare a CABasicAnimation):

Interface:

@interface CAShapeLayerAnim : CAShapeLayer
@end

Implementation:

@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

The path property on CAShapeLayer is animatable. This means that you can create one path where every y value is 0.0 and the animate from that path to the real graph. Just make sure that the paths have the same number of points. This should be easy, since you already have the loop.

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

Then you can animate the path by creation a CABasicAnimation for the @"path" key.

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

For animation you need use strokeStart and strokeEnd properties of CAShapeLayer.

See example CAShapeLayer animation in Ole Begemann blog post.

From documentation strokeStart:

The value of this property must be in the range 0.0 to 1.0. The default value of this property is 1.0.

Combined with the strokeEnd property, this property defines the subregion of the path to stroke. The value in this property indicates the relative point along the path at which to begin stroking while the strokeEnd property defines the end point. A value of 0.0 represents the beginning of the path while a value of 1.0 represents the end of the path. Values in between are interpreted linearly along the path length.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!