Wednesday, May 18, 2011

Very easy way to create pie charts in your iPhone app !

Well.. I haven't been across many pie chart creating APIs for iPhone/iPad app.. Here is my effort to make it as easy as I could for other developers looking to create pie chart in your app.

This post also makes clear the use of anti-alias stuff while you are drawing on your context.
The first pie chart diagram doesn't use the anti-alias but the second one does hence you can see in the screenshot attached with this post its looks so smooth ! For incorporating the anti-alias stuff  in your drawing you need to include only  2 lines as following:



CGContextSetAllowsAntialiasing(context, true);
CGContextSetShouldAntialias(context, true);


If any one of them above is false then you will not have anti-alias work for you.

How to use this pie-chart code? 
In MainClass:
You will see following lines

myPieClass.itemArray=[[NSArray alloc]initWithObjects:@"12",@"84",@"44",@"55",@"100"nil];
myPieClass.myColorArray=[[NSArray alloc]initWithObjects:[UIColor purpleColor],[UIColor redColor],[UIColor orangeColor],[UIColor yellowColor],[UIColor greenColor], nil];

So you give your own values to itemArray , code will automatically calculate the angle and offset  stuff for you. You also need to give the color for each segment of the pie chart. The number of items in myColorArray should be equal to number of items in itemArrayAnd according to above array values for color,  pie segment with value 12 have purple color, pie segment with value 84 will have red color.

Just to make it more clear: Suppose your created a budget application and you have 5 categories of expense type, 
now your total for category 1 is 12
total for category 2 is 84
total for category 3 is 44
total for category 4 is 55
total for category 5 is 100
  
So, you have to give here the raw values... in order to create your pie chart. Dont give angles value in itemArray as code calculates the angles itself as mentioned above.



As you can see in the picture below.



































NEW !!  MIM Chart library has been released in Alpha 1.0 version, It includes Line Graph, Bar Graph and many other kinds. You can find more info and download  HERE

5 comments:

  1. Hi, I found the link to download code also doesn't work for this one :-(

    ReplyDelete
  2. "context"undeclaired error generate
    please reply fast
    thnks for this code

    ReplyDelete
  3. Vivudh,, you need to make sure you are pasting the code in UIView (drawRect: )not UIViewcontroller

    ReplyDelete