iPhone 利用CG API画一个饼图(Pie chart) 百分比圆 以及 响应扇形点击事件

来源:互联网 发布:ip切换软件 编辑:程序博客网 时间:2024/04/23 23:48
核心函数是:CGContextAddArc(CGContextRef c, CGFloat x, CGFloat y, CGFloat radius, CGFloat startAngle, CGFloat endAngle, int clockwise)    * CGContextRef: 图形上下文    * x,y: 开始画的坐标    * radius: 半径    * startAngle, endAngle: 开始的弧度,结束的弧度    * clockwise: 画的方向(顺时针,逆时针)

有了这个函数可以画出任意扇形,所以饼图也不再话下.

#define PI 3.14159265358979323846#define radius 100static inline float radians(double degrees) {         return degrees * PI / 180; }static inline void drawArc(CGContextRef ctx, CGPoint point, float angle_start, float angle_end, UIColor* color) {        CGContextMoveToPoint(ctx, point.x, point.y);        CGContextSetFillColor(ctx, CGColorGetComponents( [color CGColor]));        CGContextAddArc(ctx, point.x, point.y, radius,  angle_start, angle_end, 0);    //CGContextClosePath(ctx);     CGContextFillPath(ctx); }- (void)drawRect:(CGRect)rect {            CGContextRef ctx = UIGraphicsGetCurrentContext();    CGContextClearRect(ctx, rect);                        float angle_start = radians(0.0);        float angle_end = radians(121.0);                drawArc(ctx, self.center, angle_start, angle_end, [UIColor yellowColor]);                        angle_start = angle_end;        angle_end = radians(228.0);                drawArc(ctx, self.center, angle_start, angle_end, [UIColor greenColor]);                angle_start = angle_end;        angle_end = radians(260);        drawArc(ctx, self.center, angle_start, angle_end, [UIColor orangeColor]);                        angle_start = angle_end;        angle_end = radians(360);        drawArc(ctx, self.center, angle_start, angle_end, [UIColor purpleColor]);}

效果:



想想,我用这个函数,画两个同圆心的扇形
大的用自己想要的颜色,小的用背景色
这样就实现了画环形了,多谢大神!


我来补充点:可以使用UIBezierPath的处理扇形区域的点击事件


原文地址:http://www.devdiv.com/forum.php?mod=viewthread&tid=38136&fromuid=36506



原创粉丝点击