In “CAShapeLayer in Depth, Part I,” we explored the creation and configuration of shape layers, looking at each of their properties in turn. While useful as a static shape drawing tool,
CAShapeLayer was built to be a powerful, easy-to-use animation class as well. Now, in Part II of “CAShapeLayer in Depth,” we’ll take a close look at each of
CAShapeLayer’s animatable properties.
The primary advantage of using shape layers for animation in place of using something like Core Graphics is that
CAShapeLayer is composited on the GPU, making it significantly faster. In fact, like practically every Core Animation animation, once a shape layer animation is committed from the main thread of an application, Core Animation does all the heavy lifting inside its own processes, leaving an application’s main thread completely free during the animation. Animating with Core Graphics, on the other hand, might require an application to render a bitmap for every frame of the animation, sending each bitmap to Core Animation to composite along with the rest of the layer hierarchy.1
As a reminder, Part II of this series will be focused on the basics of shape layer animating. Each example will be as simple as possible in order to clearly demonstrate the effects of animating each property. In the last part of this series, Part III, we’ll look at a few examples of non-trivial, real-world applications of shape layers.
- Animatable Properties
Path animations are by far the most powerful and most complex aspects of
CAShapeLayer. Path animations allow you to morph a shape layer from one shape to another, which can create very compelling UI effects if used carefully.
CAShapeLayer has the following to say about animations on the
Paths will interpolate as a linear blend of the “on-line” points; “off-line” points may be interpolated non-linearly (e.g. to preserve continuity of the curve’s derivative).
What this means is that “on-line” points—those that are explicitly specified as part of a path’s description—are interpolated by moving them in a straight line from their starting positions to their ending positions. On the other hand, “off-line” points—those that are calculated or inferred as intermediary points between “on-line” points—are potentially interpolated using more complex means, the details of which are not made available to us.
Here’s the code that produces this animation:
It’s pretty obvious that the animation itself is trivial: all it needs is another
CGPath to animate to. The hard part is constructing the right paths so the animation looks appealing. Now consider what happens when we simplify the rectangle path; after all, a rectangle can easily be represented by a path with only four unique points:2
And here’s what animating to that path looks like:3
This will almost always result in an undesirable animation. Per the documentation for
path property, the result of a path animation is undefined4 if the path being animated to has a different number of control points or segments. In this case, the second path has fewer line segments, so Core Animation actually doesn’t know what to do with the remaining line segments from the original path.5
As a general rule of thumb, your initial and animatable paths should always contain the same number of points. To make this easier while designing your shapes,6 start with the more complex path—the one with the most points or segments—involved with an animation. From there, move the points around to create the simpler shape, placing redundant points wherever they might naturally resolve in a path morphing animation.
Animating a shape’s fill color is straightforward:
One thing to keep in mind is that Core Animation always interpolates color in the RGB color space, which is unfortunate but completely understandable given the complexity of converting to better color spaces. RGB is strictly a technical color space used by computers because of the way pixels display color, so the straight line between points when linearly interpolating between two colors in an RGB color cube can pass through arbitrary colors. In the above example, you can see that the fill color appears to transition from red to dark gray to cyan. A better color space can interpolate between hue or luminosity, for example, which might create more visual continuity according to how we perceive color; however, even with a color space like HSB, the results may not look that great with a straight linear interpolation.
It turns out that interpolating between two colors in a way that is visually pleasing to the human eye can be hard and computationally expensive, especially for real-time rendering, but it can be done. For practical purposes, if a straight RGB interpolation between two colors doesn’t produce acceptable results, you may instead choose to use a keyframe animation, picking a handful of better in-between colors.
Finally, recall in Part I that
UIColor can create a pattern image fill. There’s nothing inherently unique about pattern images versus solid color fills, so you can, of course, animate to or from a pattern image as well.
Line Dash Phase
Line dash phase, or dash offset, is how far into the dash pattern the line actually starts. Animating this property gives you the “marching ants” effect:
To ensure that a dash phase animation loops seamlessly, the animation value should be twice the dash phase pattern if there’s only one element in the array and the sum of the elements otherwise.7
Though the dash phase animation is seamless, you will often see a seam at the start of the line itself. If the sum of the dash pattern array (or twice its value if there is only one element) does not evenly divide the total unit length of the shape’s path, there will be a discontinuity that can create a noticeable seam. There is no built-in method for determining the length of an arbitrary path, and the process of doing so is not trivial. Fortunately, there appears to be an open source solution available specifically for
CGPaths. In practice, for non-programmatically generated shape paths, it’s often easy enough to tweak the dash pattern until it repeats evenly.
Line width is another straightforward property to animate:
Recall that path strokes straddle the bounds of the path itself, so half the line width will be inside the path and half will be outside.
Among all the animatable properties, miter limit is the most perplexing. Briefly, miter limit determines when a miter-style line join switches to a bevel join instead. And while Core Animation does support
miterLimit as an animatable property, it actually performs no animation at all. The change to pertinent line joins happens immediately, making it a seemingly-useless property to animate. All that comes to mind is using a miter limit animation in conjunction with other shape layer animations to switch how certain lines are joined mid-animation.
Similar to fill color, animating stroke color is easy:
Stroke Start and End
A very useful pair of animatable properties is
strokeEnd. Both represent a relative point along the total path length, defined as a fraction between 0.0 and 1.0, where 0.0 indicates the beginning of the path, and 1.0 indicates the end of the path. The visible portion of the path is always the difference between
strokeEnd from 0.0 to 1.0 is commonly used to “draw on” a path:
strokeStart from 0.0 to 1.0 is commonly used to “erase” a path:
One thing to keep in mind is that both
strokeEnd are clamped to the range [0.0, 1.0]. That is, you can’t use negative values to reverse the direction of a stroke animation. To do so, just reverse the path itself using
CAShapeLayer is happy to animate the stroke of any path, regardless of its complexity. Just remember that it always animates the stroke in the order the segments or curves are added to the path. To that end, it’s not possible to animate different parts of a path concurrently. If, for example, you wanted multiple parts of a path to start drawing on together at the same time, you would need to create different shape layers for each path you wanted and animate them independently.
CAShapeLayer is a very powerful tool for creating rich, performant shapes with a variety of properties to animate. The utility of some—
miterLimit—is questionable, while the absence of others—
lineJoin—is a little disappointing. Still, especially given iOS 7’s ushered-in era of flatter design, basic shapes adorn much of modern app UI design. Morphing shapes, changing stroke line widths, and animating stroke start and end points are great ways to create compelling visual effects, and GPU-compositing of shapes makes it fast to include many of them at once in your designs without affecting render performance too adversely.
In the final part of this series on
CAShapeLayer, we’ll look at some interesting combinations of the properties discussed in the past two posts to create some neat designs and animations.
It is possible to prevent main thread-bound drawing operations by performing them asynchronously on a background thread, but this can add overhead and synchronization complexity to complex drawings. Even still, each bitmap will have to be uploaded to Core Animation every frame in order to synchronize the animation with the main run loop. ↩
Most paths will want a redundant point to draw a line back to the beginning, which means you’ll always see an extra
CGPointin your path code. You can actually call
close()on the path to automatically finish it without explicitly drawing a line to the beginning, it always draws a straight line between the last point moved to and the initial point, which may not be what you want. ↩
While I explicitly matched the SVG animation above to how Core Animation would render it, the results would likely be different depending on whatever the animation framework does when given an incongruent destination path. In most cases, though, the results would not be desirable. ↩
In fact, based on my own observation, it appears that
CAShapeLayerinterpolates between points in the same order that they’re added to the path, and missing points are animated to/from (0, 0). So while you can probably reason what the incongruent path animation would look like, you shouldn’t rely on this behavior. ↩
One of the best solutions I’ve seen for this problem, albeit only for the web, is GreenSock’s MorphSVG plugin. Regardless of the number of control points or segments, it create very impressive path animations. In my opinion, Core Animation desperately needs a comparable feature to make shape layer paths less frustrating to animate. ↩
My tool of choice is PaintCode, which is a solid vector graphics and code generation app. My experiments with Adobe Illustrator were not very good, as it appears to export strange SVGs despite manually moving the same points around. ↩
A dash pattern with only one value would still produce a solid line, so Core Animation implicitly uses the same value for the unpainted segments. ↩