Search code examples
ioscore-animationuiviewanimation

how to animate a masking effect o UIView or a contained controller


We have an iOS that we currently do an animation to set the alpha on a contained view to 0. Something like this:

[UIView animateWithDuration:1.0f animations:^{
 self.jtContained.view.alpha = 1.0f;
}];

self.jtContained is a contained controller that represents the bottom half of its container controller; this removes all of the touch functionality in this contained controller. We're thinking it might be more intuitive to have essentially an animated mask on this contained controller. Here's a quick 5 minute photoshop of what we want (ie not animating it down but rather masking out the contained controller):

enter image description here

Is there a prebuilt way of doing this using either UIView animations or Core Animation? I was even thinking of just iterating through the view and setting the pixels to 0. Sorry if this is a naive question but I find some of the Core Animation docs overwhelming.

thx in advance


Solution

  • What you want to do is to create a CAShapeLayer and make it the mask layer of your view's layer. Then add a CGPath to the shape layer that is the full size of the view. (You'd create a path that starts at one corner of your view and moves around the corners in a circle, creating a rectangular path.)

    When you want to mask away your view, you'd replace the path with another rectangular path with zero area. (The first path might walk around the corners from top_left, top_right, bottom_right, bottom_left, close. The empty path would go top_left, top_right, top_left, top_right, close.)

    Core Animation will animate the change to the path that defines the shape layer, and since the path is a mask for your view's layer, the mask animates, hiding your view.

    The key thing with making this animate correctly is that the starting and ending paths must have the same number of points. That's why I describe creating a 4-point path and another EMPTY 4-point path. When you do that, Core Animation animates the movement of the points, and you get the effect you want. If your starting and ending paths have different numbers of control points, or the control points are in a different order, "the results are undefined" and usually not at all what you want.

    What you are asking about is a reveal animation, which would simply be the reverse of what I describe above.

    I have a demo project on github called iOS-CAAnimation-group-demo (link) that shows the idea. Look at the code behind the "Mask Animation" button. That code creates a "clock wipe" animation, which is a lot more complex than the simple reveal that you want to do.

    P.S. If this post helps you, please remember to mark it as answering your question (and up-vote it.)