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

本文提供了一个使用UIKit和QuartzCore框架绘制向量图形的示例代码,包括饼图的绘制过程。通过设置图形上下文、颜色、线宽等属性,实现饼图的基本展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下类文件可帮我们用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];




转载于:https://www.cnblogs.com/lovecode/articles/2345321.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值