How to create pie chart in iPhone? [closed]
I want to show pie chart of my category by percentage.
How can I create pie chart of category percentage ?
You have to implement a class which overrides the drawRect:
method and draw the pie yourself. You'd use UIBezierPath class, specifically look into the addArcWithCenter:radius:startAngle:endAngle:clockwise: method to draw a part of a circle.
See also this article and this article.
There is API by that you can do this thing.
- MIMChart
- CorePlot Effective but not handy library.
This might be helpful with the warning that if it looks like someone else's code, it's because I worked out how to do it with web sites, and the additional warning that I did this not long after starting iPhone. People who want to tell me which bits are inefficient or wrong are welcome, I'm still learning.
static inline float radians(double degrees) { return degrees * M_PI / 180; }
// making a simple pac man shape
- (UIImage*)getImage {
UIImage* image;
if(self.completion == 100.0f) {
image = [UIImage imageNamed:@"completedTaskIcon.png"];
} else {
UIGraphicsBeginImageContext(CGSizeMake(SIDELENGTH, SIDELENGTH));
CGContextRef context = UIGraphicsGetCurrentContext();
// the image should have a clear background
[[UIColor clearColor] set];
CGRect myRect = CGRectMake(0.0f, 0.0f, SIDELENGTH, SIDELENGTH);
UIRectFill(myRect);
// color was hopefully set before this method called
[self.color set];
// centre point is required
CGFloat midx = SIDELENGTH/2;
CGFloat midy = SIDELENGTH/2;
// radius of the arc
CGFloat radius = (SIDELENGTH/2) * 0.60f;
// pie background
CGContextSetFillColor(context, CGColorGetComponents([[UIColor orangeColor] CGColor]));
CGContextBeginPath(context);
CGContextMoveToPoint(context, midx + radius, midy);
CGContextAddArc(context, midx, midy, radius, radians(0), radians(360), 0);
CGContextFillPath(context);
// pie segment
CGContextSetFillColor(context, CGColorGetComponents([[UIColor blueColor] CGColor]));
CGContextBeginPath(context);
CGContextMoveToPoint(context, midx, midy);
CGContextAddLineToPoint(context, midx + radius, midy);
CGContextAddArc(context, midx, midy, radius, radians(0), radians(360 * (self.completion / 100.0f)), 0);
CGContextFillPath(context);
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
return image;
}
Besides the proposed library in the other answers, there are two really good open source pie chart classes that I used. They look very nice, are extremely simple, have a look at them at GitHub:
XYPieChart
NBPieChart
精彩评论