代码改变世界

译:用iPhone SDK来画饼图(Pie Charts)报表

2012-02-10 14:34  张智清  阅读(544)  评论(0编辑  收藏  举报

以下类文件可帮我们用UIKit和QuartzCore框架来绘制向量图形。类似这个饼图(Pie Charts)。

// GraphView.h

#import <UIKit/UIKit.h>

@interface GraphView:UIView {
}
@end
// GraphView.m

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

// 获得图形上下文,然后清除之
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextClearRect(ctx, rect);

// 定义笔触颜色
CGContextSetRGBStrokeColor(ctx, 1, 1, 1, 1.0);
// 定义线宽
CGContextSetLineWidth(ctx, 4.0);

// 绘制饼图的一些必要值
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);
}

代码中类似snapshot_start等变量值要在程序中设定好!!。

调用示例:

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