Search code examples
objective-ccore-animationcalayerios5.1

How to animate the fill color of CALayer as it fills the color from bottom to top in iPhone sdk


I am trying to animate the filling of a CALayer from bottom to top with a duration. I need ur help and any idea for achieving this.

I tried like this:

CABasicAnimation *pathAnimation = 
 [CABasicAnimation animationWithKeyPath:@"fillColor"];
pathAnimation.duration = 5.0;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
[annotation addAnimation:pathAnimation forKey:@"fillColorAnimation"];

But no change....

Any ideas will be appreciated.

Thanks all.


Solution

  • If you want to fill an arbitrary shape with a color as if the color is flowing like water from the bottom to the top, you'll actually need TWO shape layers or more.

    Create your shape layer fully formed, with the fill color in place. Then create a second shape layer with a path that's 4 lines forming a rectangle the same size as your first shape layer. Initially, make the rectangle be a horizontal line at the bottom of the first shape layer, with zero area. Install the second shape layer as a mask layer of the first shaper layer.

    Create an animation that changes the shape of the second (mask) layer from a zero-thickness line at the bottom to the full bounds of the first shape layer. This will cause the second shape layer to animate a rectangle growing from the bottom to the top of the first shape layer's bounds. Since the second shape layer is a mask for the first, the animation will cause the first shape layer to be revealed from top to bottom as the animation runs.

    If you need the outline of the shape to be in place from the beginning of the animation and animate filling in the interior of the shape, then add a copy of the shape layer on top of the first shape layer, set to only stroke the shape, not fill it. Make that layer non-opaque. It should draw the outline of the shape, and the animation of the other shape layer/mask pair should fill the interior underneath the outline.