iPhone 利用CG API画一个饼图(Pie chart)

 

核心函数是:CGContextAddArc(CGContextRef c, CGFloat x, CGFloat y, CGFloat radius, CGFloat startAngle, CGFloat endAngle, intclockwise)

 

  • CGContextRef: 图形上下文
  • x,y: 开始画的坐标
  • radius: 半径
  • startAngle, endAngle: 开始的弧度,结束的弧度
  • clockwise: 画的方向(顺时针,逆时针)
 
有了这个函数可以画出任意扇形,所以饼图也不再话下. 
Java代码 
  1. #define PI 3.14159265358979323846  
  2. #define radius 100  
  3.   
  4. static inline float radians(double degrees) {   
  5.     return degrees * PI / 180;   
  6. }  
  7.   
  8. static inline void drawArc(CGContextRef ctx, CGPoint point, float angle_start, float angle_end, UIColor* color) {  
  9.     CGContextMoveToPoint(ctx, point.x, point.y);  
  10.     CGContextSetFillColor(ctx, CGColorGetComponents( [color CGColor]));      
  11.     CGContextAddArc(ctx, point.x, point.y, radius,  angle_start, angle_end, 0);  
  12.     //CGContextClosePath(ctx);   
  13.     CGContextFillPath(ctx);   
  14. }  
  15.   
  16. - (void)drawRect:(CGRect)rect {  
  17.       
  18.     CGContextRef ctx = UIGraphicsGetCurrentContext();  
  19.     CGContextClearRect(ctx, rect);  
  20.       
  21.       
  22.     float angle_start = radians(0.0);  
  23.     float angle_end = radians(121.0);     
  24.     drawArc(ctx, self.center, angle_start, angle_end, [UIColor yellowColor]);  
  25.       
  26.       
  27.     angle_start = angle_end;  
  28.     angle_end = radians(228.0);   
  29.     drawArc(ctx, self.center, angle_start, angle_end, [UIColor greenColor]);  
  30.   
  31.       
  32.     angle_start = angle_end;  
  33.     angle_end = radians(260);  
  34.     drawArc(ctx, self.center, angle_start, angle_end, [UIColor orangeColor]);  
  35.       
  36.       
  37.     angle_start = angle_end;  
  38.     angle_end = radians(360);  
  39.     drawArc(ctx, self.center, angle_start, angle_end, [UIColor purpleColor]);  
  40. }  
 



id 博主 = [[KILONET.CNBLOGS.COM alloc] initWithValue:@"天堂向右,我依然向左"

              网名:@"老舟"

              兴趣:@"影音,阅读"

              动态:@"系统架构设计,Android通信模块开发"

              网址:@"http://kilonet.cnblogs.com"
              签名:@"--------------------------------------------------

                              Stay Hungry , Stay Foolish

                              求  知  若  渴,处  事  若  愚

                          --------------------------------------------------"

              ];         // Never Release

原文地址:https://www.cnblogs.com/KiloNet/p/1807316.html