Animating Pie Slices using a custom CALayer

It’s going to be a rather long post, so if you want to jump around, here are your way points:

  1. First steps
    1. A path for the slice
    2. Animating the pie-slice
  2. Raising the level of abstraction
    1. Custom CALayer, the PieSliceLayer
    2. Rendering the PieSliceLayer
  3. It all comes together in PieView
    1. Managing the slices
  4. Demo and Source code

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 override drawRect:. 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. Use CAGradientLayer, CAShapeLayer or CATiledLayer
  • Create a custom UIView and render a CALayer 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.

 1-(CAShapeLayer *)createPieSlice {
 2	CAShapeLayer *slice = [CAShapeLayer layer];
 3	slice.fillColor = [UIColor redColor].CGColor;
 4	slice.strokeColor = [UIColor blackColor].CGColor;
 5	slice.lineWidth = 3.0;
 7	CGFloat angle = DEG2RAD(-60.0);
 8	CGPoint center = CGPointMake(100.0, 100.0);
 9	CGFloat radius = 100.0;
11	UIBezierPath *piePath = [UIBezierPath bezierPath];
12	[piePath moveToPoint:center];
14	[piePath addLineToPoint:CGPointMake(center.x + radius * cosf(angle), center.y + radius * sinf(angle))];
16	[piePath addArcWithCenter:center radius:radius startAngle:angle endAngle:DEG2RAD(60.0) clockwise:YES];
18//	[piePath addLineToPoint:center];
19	[piePath closePath]; // this will automatically add a straight line to the center
20	slice.path = piePath.CGPath;
22	return slice;
  • 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:

Unit Coordinates

  • 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.

UIBezierPath Render

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:

UIBezierPath Render

To achieve that, lets refactor the code a bit and move the path creation into its own method.

 2				radius:(CGFloat)radius
 3				startAngle:(CGFloat)degStartAngle
 4				endAngle:(CGFloat)degEndAngle {
 6	UIBezierPath *piePath = [UIBezierPath bezierPath];
 7	[piePath moveToPoint:center];
 9	[piePath addLineToPoint:CGPointMake(center.x + radius * cosf(DEG2RAD(degStartAngle)), center.y + radius * sinf(DEG2RAD(degStartAngle)))];
11	[piePath addArcWithCenter:center radius:radius startAngle:DEG2RAD(degStartAngle) endAngle:DEG2RAD(degEndAngle) clockwise:YES];
13	//	[piePath addLineToPoint:center];
14	[piePath closePath]; // this will automatically add a straight line to the center
16	return piePath.CGPath;
19-(CAShapeLayer *)createPieSlice {
21	CGPoint center = CGPointMake(100.0, 100.0);
22	CGFloat radius = 100.0;
24	CGPathRef fromPath = [self createPieSliceWithCenter:center radius:radius startAngle:-60.0 endAngle:60.0];
25	CGPathRef toPath = [self createPieSliceWithCenter:center radius:radius startAngle:120.0 endAngle:-120.0];
27	CAShapeLayer *slice = [CAShapeLayer layer];
28	slice.fillColor = [UIColor redColor].CGColor;
29	slice.strokeColor = [UIColor blackColor].CGColor;
30	slice.lineWidth = 3.0;
31	slice.path = fromPath;
34	CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"path"];
35	anim.duration = 1.0;
37	// flip the path
38	anim.fromValue = (__bridge id)fromPath;
39	anim.toValue = (__bridge id)toPath;
40	anim.removedOnCompletion = NO;
41	anim.fillMode = kCAFillModeForwards;
43	[slice addAnimation:anim forKey:nil];
44	return slice;

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:

Path Animation

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.
 1#import <QuartzCore/QuartzCore.h>
 3@interface PieSliceLayer : CALayer
 6@property (nonatomic) CGFloat startAngle;
 7@property (nonatomic) CGFloat endAngle;
 9@property (nonatomic, strong) UIColor *fillColor;
10@property (nonatomic) CGFloat strokeWidth;
11@property (nonatomic, strong) UIColor *strokeColor;
 1#import "PieSliceLayer.h"
 3@implementation PieSliceLayer
 5@dynamic startAngle, endAngle;
 6@synthesize fillColor, strokeColor, strokeWidth;
  • Override actionForKey: and return a CAAnimation that prepares the animation for that property. In our case, we will return an animation for the startAngle and endAngle 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 the presentationLayer 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 our startAngle and endAngle properties will require a redraw.

 1-(id<CAAction>)actionForKey:(NSString *)event {
 2	if ([event isEqualToString:@"startAngle"] ||
 3		[event isEqualToString:@"endAngle"]) {
 4		return [self makeAnimationForKey:event];
 5	}
 7	return [super actionForKey:event];
10- (id)initWithLayer:(id)layer {
11	if (self = [super initWithLayer:layer]) {
12		if ([layer isKindOfClass:[PieSliceLayer class]]) {
13			PieSliceLayer *other = (PieSliceLayer *)layer;
14			self.startAngle = other.startAngle;
15			self.endAngle = other.endAngle;
16			self.fillColor = other.fillColor;
18			self.strokeColor = other.strokeColor;
19			self.strokeWidth = other.strokeWidth;
20		}
21	}
23	return self;
26+ (BOOL)needsDisplayForKey:(NSString *)key {
27	if ([key isEqualToString:@"startAngle"] || [key isEqualToString:@"endAngle"]) {
28		return YES;
29	}
31	return [super needsDisplayForKey:key];

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.

 1-(void)drawInContext:(CGContextRef)ctx {
 3	// Create the path
 4	CGPoint center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
 5	CGFloat radius = MIN(center.x, center.y);
 7	CGContextBeginPath(ctx);
 8	CGContextMoveToPoint(ctx, center.x, center.y);
10	CGPoint p1 = CGPointMake(center.x + radius * cosf(self.startAngle), center.y + radius * sinf(self.startAngle));
11	CGContextAddLineToPoint(ctx, p1.x, p1.y);
13	int clockwise = self.startAngle > self.endAngle;
14	CGContextAddArc(ctx, center.x, center.y, radius, self.startAngle, self.endAngle, clockwise);
16	CGContextClosePath(ctx);
18	// Color it
19	CGContextSetFillColorWithColor(ctx, self.fillColor.CGColor);
20	CGContextSetStrokeColorWithColor(ctx, self.strokeColor.CGColor);
21	CGContextSetLineWidth(ctx, self.strokeWidth);
23	CGContextDrawPath(ctx, kCGPathFillStroke);

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.

1#import <UIKit/UIKit.h>
3@interface PieView : UIView
5@property (nonatomic, strong) NSArray *sliceValues;
7-(id)initWithSliceValues:(NSArray *)sliceValues;
  1#import "PieView.h"
  2#import "PieSliceLayer.h"
  3#import <QuartzCore/QuartzCore.h>
  5#define DEG2RAD(angle) angle*M_PI/180.0
  8@interface PieView() {
  9	NSMutableArray *_normalizedValues;
 10	CALayer *_containerLayer;
 16@implementation PieView
 17@synthesize sliceValues = _sliceValues;
 19-(void)doInitialSetup {
 20	_containerLayer = [CALayer layer];
 21	[self.layer addSublayer:_containerLayer];
 24- (id)initWithFrame:(CGRect)frame
 26    self = [super initWithFrame:frame];
 27    if (self) {
 28		[self doInitialSetup];
 29    }
 31    return self;
 34-(id)initWithCoder:(NSCoder *)aDecoder {
 35	if (self = [super initWithCoder:aDecoder]) {
 36		[self doInitialSetup];
 37	}
 39	return self;
 42-(id)initWithSliceValues:(NSArray *)sliceValues {
 43	if (self) {
 44		[self doInitialSetup];
 45		self.sliceValues = sliceValues;
 46	}
 48	return self;
 51-(void)setSliceValues:(NSArray *)sliceValues {
 52	_sliceValues = sliceValues;
 54	_normalizedValues = [NSMutableArray array];
 55	if (sliceValues) {
 57		// total
 58		CGFloat total = 0.0;
 59		for (NSNumber *num in sliceValues) {
 60			total += num.floatValue;
 61		}
 63		// normalize
 64		for (NSNumber *num in sliceValues) {
 65			[_normalizedValues addObject:[NSNumber numberWithFloat:num.floatValue/total]];
 66		}
 67	}
 69	[self updateSlices];
 72-(void)updateSlices {
 74	_containerLayer.frame = self.bounds;
 76	// Adjust number of slices
 77	if (_normalizedValues.count > _containerLayer.sublayers.count) {
 79		int count = _normalizedValues.count - _containerLayer.sublayers.count;
 80		for (int i = 0; i < count; i++) {
 81			PieSliceLayer *slice = [PieSliceLayer layer];
 82			slice.strokeColor = [UIColor colorWithWhite:0.25 alpha:1.0];
 83			slice.strokeWidth = 0.5;
 84			slice.frame = self.bounds;
 86			[_containerLayer addSublayer:slice];
 87		}
 88	}
 89	else if (_normalizedValues.count < _containerLayer.sublayers.count) {
 90		int count = _containerLayer.sublayers.count - _normalizedValues.count;
 92		for (int i = 0; i < count; i++) {
 93			[[_containerLayer.sublayers objectAtIndex:0] removeFromSuperlayer];
 94		}
 95	}
 97	// Set the angles on the slices
 98	CGFloat startAngle = 0.0;
 99	int index = 0;
100	CGFloat count = _normalizedValues.count;
101	for (NSNumber *num in _normalizedValues) {
102		CGFloat angle = num.floatValue * 2 * M_PI;
104		NSLog(@"Angle = %f", angle);
106		PieSliceLayer *slice = [_containerLayer.sublayers objectAtIndex:index];
107		slice.fillColor = [UIColor colorWithHue:index/count saturation:0.5 brightness:0.75 alpha:1.0];
108		slice.startAngle = startAngle;
109		slice.endAngle = startAngle + angle;
111		startAngle += angle;
112		index++;
113		hue += num.floatValue;
114	}

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.