Animate drawing the fill of a CAShapeLayer
Asked Answered
N

2

10

I've been playing around with drawing a path using a CAShapeLayer as outlined in this great article, http://oleb.net/blog/2010/12/animating-drawing-of-cgpath-with-cashapelayer, but I'm wondering if there's a way to animate the filling of a layer.

For example, I have some text I want to draw on the screen, but I've only been able to draw the stroke of the text and not the fill. Another example, I have a star shape that I would like to animate it being filled in.

Is this possible using a CAShapeLayer or other object?

Thanks!

Niagara answered 4/5, 2011 at 16:28 Comment(1)
What kind of animation do you have in mind? Moving stroke? Filling up from the bottom to top or left to right? Cross-faded color?Mistook
T
2

Its most of the time the same code, you just have to set different values for fromValue and toValue of your CABasicAnimation. I created a category which returns me a CABasicAnimation:

Animation for StrokeEnd

+ (CABasicAnimation *)animStrokeEndWithDuration:(CGFloat)dur
                                       delegate:(id)target{
    CABasicAnimation *animLine = 
     [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    [animLine setDuration:dur];
    [animLine setFromValue:[NSNumber numberWithFloat:0.0f]];
    [animLine setToValue:[NSNumber numberWithFloat:1.0f]];
    [animLine setRemovedOnCompletion:NO];
    [animLine setFillMode:kCAFillModeBoth];
    [animLine setDelegate:target];
    [animLine setTimingFunction:
     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];

    return animLine;
}

Animation for fillColor

+ (CABasicAnimation *)animFillColorWithDur:(CGFloat)dur
                                  startCol:(UIColor *)start
                                  endColor:(UIColor *)end
                                  delegate:(id)target{

    CABasicAnimation *animFill = 
     [CABasicAnimation animationWithKeyPath:@"fillColor"];
    [animFill setDuration:dur];
    [animFill setFromValue:(id)start.CGColor];
    [animFill setToValue:(id)end.CGColor];
    [animFill setRemovedOnCompletion:NO];
    [animFill setDelegate:target];
    [animFill setFillMode:kCAFillModeBoth];

    return animFill;
}

The returned CABasicAnimation just has to be added to a CAShapeLayer:

[_myShapeLayer addAnimation:returnedAnimation forKey:@"animKey"]
Telophase answered 3/9, 2014 at 14:57 Comment(0)
A
0

Yes, it is possible.

CAShapeLayers have a fillColor property which is animatable.

It works the same way as changing the strokeEnd / strokeStart like you've already done with with your animation.

Aranda answered 8/3, 2012 at 0:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.