http://blog.pixelingene.com/2012/02/animating-pie-slices-using-a-custom-calayer/#C1
It’s going to be a rather long post, so if you want to jump around, here are your way points:
With a powerful platform like iOS, it is not surprising to have a variety of options for drawing. Picking the one that works best may sometimes require a bit of experimentation. Case in point: a pie chart whose slices had to be animated as the values changed over time. In this blog post, I would like to take you through various stages of my design process before I ended up with something close to what I wanted. So lets get started.
First steps
Lets quickly look at the array of options that we have for building up graphics in iOS:
- Use the standard Views and Controls in
UIKit
and create a view hierarchy - Use the
UIAppearance
protocol to customize standard controls - Use
UIWebView
and render some complex layouts in HTML + JS. This is a surprisingly viable option for certain kinds of views - Use
UIImageView
and show a pre-rendered image. This is sometimes the best way to show a complex graphic instead of building up a series of vectors. Images can be used more liberally in iOS and many of the standard controls even accept an image as parameter. - Create a custom
UIView
and overridedrawRect:
. This is like the chain-saw in our toolbelt. Used wisely it can clear dense forests of UI challenges. - Apply masking (a.k.a. clipping) on vector graphics or images. Masking is often underrated in most toolkits but it does come very handy.
- Use Core Animation Layers:
CALayer
with shadows, cornerRadius or masks. UseCAGradientLayer
,CAShapeLayer
orCATiledLayer
- Create a custom
UIView
and render aCALayer
hierarchy
As you can see there are several ways in which we can create an interactive UI control. Each of these options sit at a different level of abstraction in the UI stack. Choosing the right combination can thus be an interesting thought-exercise. As one gains more experience, picking the right combination will become more obvious and also be a lot faster.
A path for the slice
With that quick overview of the UI options in iOS, lets get back to our problem of building an animated Pie Chart. Since we are talking about animation, it is natural to think about Core Animation and CALayers. In fact, the choice of a CAShapeLayer
with a path for the pie-slice is a good first step. Using the UIBezierPath
class, it is easier than using a bunch of CGPathXXX calls.
- The path consists of two radial lines originating at the center of the cirlce, with an arc between the end-points of the lines
- The angles in the call to
addArcWithCenter
use the following unit-coordinate system:
-
DEG2RAD
is a simple macro that converts from degrees to radians - When rendered the pie slice looks like below. The background gray circle was added to put the slice in the context of the whole circle.
Animating the pie-slice
Now that we know how to render a pie-slice, we can start looking at animating it. When the angle of the pie-slice changes we would like to smoothly animate to the new slice. Effectively the pie-slice will grow or shrink in size, like a radial fan of cards spreading or collapsing. This can be considered as a change in the path
of the CAShapeLayer
. Since CAShapeLayer
naturally animates changes to the path
property, we can give it a shot and see if that works. So, let’s say, we want to animate from the current slice to a horizontally-flipped slice, like so:
To achieve that, lets refactor the code a bit and move the path creation into its own method.
In the refactored code, createPieSlice:
just calls the createPieSliceWithCenter:radius:startAngle:endAngle
function for the from and to-paths and sets up an animation between these two paths. In action, this looks like so:
Yikes! That is definitely not what we expected. CAShapeLayer
is morphing the paths rather than growing or shrinking the pie slices. Of course, this means we need to adopt more stricter measures for animating the pie slices.
Raising the level of abstraction
Clearly CAShapeLayer doesn’t understand pie-slices and has no clue about how to animate a slice in a natural manner. We definitely need more control around how the pie slice changes. Luckily we have an API that gives a hint at the kind of abstraction we need: a pie slice described in terms of {startAngle, endAngle}
. This way our parameters are more strict and not as flexible as the points of a bezier path. By making these parameters animatable, we should be able to animate the pie-slices just the way we want.
Applying this idea to our previous animation example, the path can be said to be changing from {-60.0, 60.0}
to {120.0, -120.0}
. By animating the startAngle
and endAngle
, we should be able to make the animation more natural. In general, if you find yourself tackling a tricky problem like this, take a step back and check if you are at the right level of abstraction.
Custom CALayer, the PieSliceLayer
If a CAShapeLayer can’t do it, we probably need our own custom CALayer
. Let’s call it the PieSliceLayer
and give it two properties: … you guessed it… startAngle
and endAngle
. Any change to these properties will cause the custom layer to redraw and also animate the change. This requires following a few standard procedures as prescribed by Core Animation Framework.
- Firstly don’t
@synthesize
the animatable properties and instead mark them as@dynamic
. This is required because Core Animation does some magic under the hood to track changes to these properties and call appropriate methods on your layer.
-
Override
actionForKey:
and return aCAAnimation
that prepares the animation for that property. In our case, we will return an animation for thestartAngle
andendAngle
properties. -
Override
initWithLayer:
to copy the properties into the new layer. This method gets called for each frame of animation. Core Animation makes a copy of thepresentationLayer
for each frame of the animation. By overriding this method we make sure our custom properties are correctly transferred to the copied-layer. -
Finally we also need to override
needsDisplayForKey:
to tell Core Animation that changes to ourstartAngle
andendAngle
properties will require a redraw.
With that we now have a custom PieSliceLayer that animates changes to the angle-properties. However the layer does not display any visual content. For this we will override the drawInContext:
method.
Rendering the PieSliceLayer
Here we draw the slice just the way we did earlier. Instead of using UIBezierPath
, we now go with the Core Graphics calls. Since the startAngle
and endAngle
properties are animatable and also marked for redraw, this layer will be rendered each frame of the animation. This will give us the desired animation when the slice changes its inscribed angle.
It all comes together in PieView
When we originally started, we wanted to build a Pie Chart that animated changes to its slices. After some speed bumps we got to a stage where a single slice could be described in terms of start/end angles and have any changes animated.
If we can do one slice, we can do multiples! A Pie Chart is a visualization for an array of numbers, where each numbers is an instance of the PieSliceLayer
. The size of a slice depends on its relative value within the array. An easy way to get the relative value is to normalize the array and use the normal value [0, 1]
to arrive at the angle of the slice, ie. normal * 2 * M_PI
. For example, if the normal value is 0.5, the angle of the slice will be M_PI
or 180°.
Managing the slices
The PieView
manages the slices in a way that makes sense for a Pie Chart. Given an array of numbers, the PieView
takes care of normalizing the numbers, creating the right number of slices and positioning them correctly in the pie. Since PieView
will be a subclass of UIView, we also have the option to introduce some touch interaction later. Having a UIView that hosts a bunch of CALayers is a common approach when dealing with an interactive element like the PieChart.
The PieView
exposes a sliceValues
property which is an NSArray
of numbers. When this property changes, PieView
manages the CRUD around the PieSliceLayers
. If there are more numbers than slices, PieView
will add the missing slices. If there are fewer numbers than slices, it removes the excess. All the existing slices are updated with the new numbers. All of this happens in the updateSlices
method.
There is one thing we didn’t do yet, which is enabling some touch interaction. I’ll leave that as a reader exercise for now.
Demo and Source code
With all that reading you did so far, your eyes are probably thirsty for some visuals. Well, treat yourself with the YouTube video and the github source on the side.