September 16, 2014

Drawing Pie Charts using iPhone SDK

Here’s one way to draw a PIE chart using the latest iPhone SDK. There are a ton of tutorials out there that let you get started with the iPhone app development itself and I am by no means any authoritative source on learning how to develop one. Having said that, here’s a class file that will help you use the UIKit and Quartz to draw vector graphics.


An example of the pie charts the code base generates is below (a screenshot):

iPhone SDK

And now, for the code:

GraphView.h

1
2
3
4
5
6
7
8
9
10
11
12
#
#(nothing to see here)
#
 
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
 
@interface GraphView : UIView {
 
}
 
@end

GraphView.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#import "GraphView.h"
 
#define PI 3.14159265358979323846
static inline float radians(double degrees) { return degrees * PI / 180; }
 
@implementation GraphView
 
- (void)drawRect:(CGRect)rect {
 
	CGRect parentViewBounds = self.bounds;
	CGFloat x = CGRectGetWidth(parentViewBounds)/2;
	CGFloat y = CGRectGetHeight(parentViewBounds)*0.55;
 
    // Get the graphics context and clear it
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextClearRect(ctx, rect);
 
	// define stroke color
	CGContextSetRGBStrokeColor(ctx, 1, 1, 1, 1.0);
 
	// define line width
	CGContextSetLineWidth(ctx, 4.0);
 
 
       // need some values to draw pie charts
 
        double snapshotCapacity =20;
        double rawCapacity = 100;
        double systemCapacity = 1;
 
	int offset = 5;
	double pie1_start = 315.0;	
	double pie1_finish = snapshotCapacity *360.0/rawCapacity; 
	double system_finish = systemCapacity*360.0/rawCapacity;
 
    CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor greenColor] CGColor]));
    CGContextMoveToPoint(ctx, x+2*offset, y);     
    CGContextAddArc(ctx, x+2*offset, y, 100,  radians(snapshot_start), radians(snapshot_start+snapshot_finish), 0); 
    CGContextClosePath(ctx); 
    CGContextFillPath(ctx); 
 
	// system capacity 
	CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor colorWithRed:15 green:165/255 blue:0 alpha:1 ] CGColor]));
	CGContextMoveToPoint(ctx, x+offset,y);     
    CGContextAddArc(ctx, x+offset, y, 100,  radians(snapshot_start+snapshot_finish+offset), radians(snapshot_start+snapshot_finish+system_finish), 0); 
    CGContextClosePath(ctx); 
    CGContextFillPath(ctx); 
 
	/* data capacity */
	CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor colorWithRed:99/255 green:184/255 blue:255/255 alpha:1 ] CGColor]));
	CGContextMoveToPoint(ctx, x, y);     
    CGContextAddArc(ctx, x, y, 100,  radians(snapshot_start+snapshot_finish+system_finish+offset), radians(snapshot_start), 0); 
    CGContextClosePath(ctx); 
    CGContextFillPath(ctx);	
}

There are some variables such as snapshot_start etc in the code that are missing values, cause I picked this code out of a larger program I am writing.

Comments

  1. This doesn’t work, where is snapshot_start defined? Have you even tried to run this? If you have, you are missing something out.

  2. Hi cak

    yes it does work. snapshot_start is just a variable.. define whatever variable you prefer and some values to actually draw the pie charts. I will upload some pictures shortly..

  3. Bob Donahue says:

    I’m trying to find a general data plotting library for the iPhone.

    Seems weird that I’d have to develop it from scratch, just to do a simple X,Y scatter plot or a bar graph.

    Are you aware of any existing packages?

    Thanks in advance,
    Bob

  4. Bob

    You may want to take a look at the following packages

    http://developer.snowmintcs.com/frameworks/sm2dgraphview/
    http://sourceforge.net/projects/narrative

    There’s always Quartz to draw graphs from scratch, as you mentioned. I use Quartz but I might take a look at those packages myself, given some time.

  5. Hi,
    when i run this code got blank white screen only. can you please submit the steps how to execute this code from begin in short.

    just like

    1. select window base application
    2. add GraphView.h and GraphView.m

    .
    .
    . finish

    like this.

  6. Hi Rajeev ,
    I desperately need pie chart code. Please help me out.

  7. why are you defining PI on line 3 if you can use the constant M_PI?

  8. Been a while since I picked up programming, so it’s a case of blissful ignorance!

  9. thanks for the excelent post, need to integrate into my app

  10. this example worked great ! To make it work out of the box, replace the CGxxxx stuff at the bottom with this: It just uses the pie1_start, and the pie1_finish.

    CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor greenColor] CGColor]));
    CGContextMoveToPoint(ctx, x+2*offset, y);
    CGContextAddArc(ctx, x+2*offset, y, 100, radians(0), radians(0), 0);
    CGContextClosePath(ctx);
    CGContextFillPath(ctx);

    // system capacity
    CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor colorWithRed:15 green:165/255 blue:0 alpha:1 ] CGColor]));
    CGContextMoveToPoint(ctx, x+offset,y);
    CGContextAddArc(ctx, x+offset, y, 100, radians(pie1_start), radians(pie1_finish), 0);
    CGContextClosePath(ctx);
    CGContextFillPath(ctx);

    /* data capacity */
    CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor colorWithRed:99/255 green:184/255 blue:255/255 alpha:1 ] CGColor]));
    CGContextMoveToPoint(ctx, x, y);
    CGContextAddArc(ctx, x, y, 100, radians(pie1_finish), radians(pie1_start), 0);
    CGContextClosePath(ctx);
    CGContextFillPath(ctx);

    to add it to your main window just put these lines in Your’AppDelegate.m’

    GraphView *graph = [[GraphView alloc] initWithFrame:CGRectMake(0.0, 20.0, 320.0, 460.0)];
    [window addSubview:graph];

  11. Sohel Taslim says:

    It works for me without any problem. Nice documentation.
    Thanks for the work.
    I am looking for more better resource. Your code will help me to build my expected one.

  12. Core Plot framework provides a better way to create Pie Charts. You can use even custom gradients for shading the Pie Slices. This tutorial will show you how Core Plot can be used to build Pie Charts in iPhone.

  13. Thanks for sharing! The screenshots for core plot look impressive!

  14. Dave Janssen says:

    Thanks for the post. I tried using core-plot, but is doesn’t seem to allow you to add labels to slices in a pie chart, at least not at the moment. So I will use Quartz for the time being.

  15. Nice tutorial. I made something much more sophisticated. 3D charts with user interaction available :)

    there is new, nice Pie Chart 3D library. 3D charts which you can rotate and scale with fingers + protocol for getting information about tapped slice

    http://iphone.orpi.pl/?p=20

  16. Hi Rajeev,
    Thanks for the code,
    rendering of pie chart is ok but can you give me an idea of how to identify the touch event on different pie slices. if you know a way please help me out regarding this.

    With Thanks
    Naren Mudgal

  17. Well…this piece of code is definetly quite strange…

    where does the red color come from? I changed every value, but it stays always red…The blue color can be changed. The red not.

  18. For me error coming in this line.

    CGRect parentViewBounds = self.bounds;

    error:request for member ‘bounds’ in something not a structure or union

    Exactly I want to draw a pie chart in my iphone application…Help me out to do this….

  19. Rob Parry says:

    Line 50:
    CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor colorWithRed:99/255 green:184/255 blue:255/255 alpha:1 ] CGColor]));
    is equivalent to:
    CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor colorWithRed:0 green:0 blue:1 alpha:1 ] CGColor]));
    As we all know, in C (and Objective-C), 99/255 = 184/255 = 0, 255/255 = 1.
    I think the intention was to use 99.0/255.0, 184.0/255.0 & 1.0?

  20. I am also getting the same error? missing any library ?

  21. even though i specified the values for snapshot_start and snapshot_stop still am getting the same white screen just tel me how to render the graph.thanks in advance…

  22. hey. I just found a code which is very easy to use.. It took me only 5 mins to put it into my app. http://soulwithmobiletechnology.blogspot.com/2011/05/very-easy-way-to-create-pie-charts-in.html

  23. JItendra Mandal says:

    HI rajeev

    I want to draw line graph (like market NSE BSE stock graph with time) how can we do that i googled a lot but it give coreplot and S7graphview both are not useful for me..

    Please help

  24. You should be using a standard macro such as:

    #define degreesToRadian(x) (CGFloat)M_PI * (x) / (CGFloat)180.0 )

Speak Your Mind

*