如何在iPhone中创建饼图?

时间:2011-01-22 07:50:41

标签: iphone pie-chart

我想按百分比显示我的类别的饼图。

如何创建类别百分比饼图?

4 个答案:

答案 0 :(得分:4)

您必须实现一个覆盖drawRect:方法的类并自己绘制饼图。您使用UIBezierPath类,特别是查看addArcWithCenter:radius:startAngle:endAngle:clockwise:方法以绘制圆的一部分。

另请参阅this articlethis article

答案 1 :(得分:3)

有API可以做到这一点。

  1. MIMChart
  2. CorePlot有效但不方便的图书馆。

答案 2 :(得分:1)

这可能有助于警告,如果它看起来像别人的代码,那是因为我弄清楚如何使用网站,以及我在启动iPhone后不久做的额外警告。那些想告诉我哪些位效率低或者错误的人都欢迎,我还在学习。

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;
}

答案 3 :(得分:0)

除了在其他答案中提出的库,我使用了两个非常好的开源饼图类。它们看起来非常漂亮,非常简单,在GitHub看一下它们: