SwiftUI: Animating Timing Curves

When you animate a property in SwiftUI, the value gets interpolated using an interpolation function, represented by the Animation type. For example, if you animate from x = 200 to x = 400 using a 1-second linear animation, the value gets interpolated linearly. After half a second, the value will be 300, and after .75 seconds it will be 350.

For a more natural animation, an easeInOut timing function is often used. This is an animation that starts slowly, gets progressively faster towards the halfway point, and then slows down again. This is reminiscent of how objects in the real world behave: as you apply a force to an object, the velocity increases, overcoming inertia; when you stop applying the force, the velocity decreases due to friction.

We wanted to know what the timing curves were for all the built-in animations. To plot them, we used something of a hack: a GeometryEffect with a single CGFloat value that gets animated from 0 to 1. Anytime SwiftUI sets that value, we record the value and the corresponding time, and save that into an array. Then we simply create a number of different animations, animate a random view using the custom geometry effect, and plot out all those values.

Here’s the result:

Animation Timing Curves

It’s interesting to see that the default animation is indeed an .easeInOut with a duration of 0.35 seconds, and how the interpolating spring overshoots and then comes back. The non-auto-reversing repeat animation seems strange at first, but it turned out to be useful for us in episode 165, where we showed how to animate along a path.

The code we used to generate this is available as a gist.

For more reading on animations, check out our issue on animations from 2014 — it still contains a lot of relevant advice! In particular, the Animations Explained article by Robert Böhnke goes into detail about animation curves. Another interesting read is the Advanced SwiftUI Animations series by The SwiftUI Lab, which shows many different ways to implement animations in SwiftUI.

Our SwiftUI Collection contains over five hours of video and growing. To support our experiments, and learn with us, subscribe here.

Stay up-to-date with our newsletter or follow us on Twitter.

Back to the Blog

recent posts