A look at UIView Animation Curves (Part 3)
In part 1, we had a look at the curves available to UIView animations.
enum UIViewAnimationCurve : Int {
case EaseInOut
case EaseIn
case EaseOut
case Linear
}
While these are often good enough, you may find yourself in a situation where you want to define your own custom animation curve. Perhaps you are working with a designer who wants you to get an animation exactly right. This is where we hit a limit with UIView animations. We now need to look elsewhere.
Custom curves using Core Animation
Let’s take that scenario where a designer asks us to make an animation pixel perfect. We glimpse over their fancy 5K retina display and are shown how their animation curve is drawn.
OK, so the lower control point is set to the 5th vertical line and 20%. The upper control point is set to the 2nd line and 90%. We note down these values and lean back again.
Let’s translate that to Swift using Core Animation.
This code looks quite different from our earlier UIView animation based code. But in principle, it’s doing the same thing. We transform the scale from 0 to 1 and use a duration of a second, just as before. The fill mode and removed on completion flag is specified for the transform to remain on completion. Without it, it reverts back to a scale of 0. Also note that we have to apply the animation to a Core Animation layer (which we find on all UIViews).
Let’s have a look at our animation. The curve here may look slightly different due to the aspect ratio but it’s more or less identical.
It can be quite tricky to draw custom curves without access to motion graphics software. Just feeding Core Animation code random input won’t get you too far. To make the process easier, I have prepared a playground which will enable you to see the curve while running the animation (see the bottom of this post).
If you are unfamiliar with cubic bezier curves, let us finish up by having a quick look under the hood. This animation illustrates how our curve was constructed using the two control points we noted down earlier:
Wrapping up
This was the last post on this topic. If you have read all parts, I hope you now have a better understanding of animation curves. Head over to GitHub and download CustomAnimationCurve.playground if you’d like to have a play. Just ensure you open up the Assistant Editor or you won’t be able to see the output. Until next time…
Update
Since I wrote this post, I’ve learned that there actually is a way to use custom animation curves on UIView animations.
The above code will override the UIView animation curve with our custom curve. I recommend reading this post for further info on CATransactions.