绘制饼图的原理很简单,首先绘制扇形,然后在中央添加一个圆形View,计算每个部分所占角度就是用每部分的比例*360就是该部分所占的角度。绘制扇形的主要方法:
- CGContextAddArc(CGContextRef __nullable c, CGFloat x, CGFloat y,
- CGFloat radius, CGFloat startAngle, CGFloat endAngle, int clockwise)
计算角度的主要代码:
- CGFloat degree=(count/allCount)*(360.f-2*self.dataSource.count);
角度转弧度主要代码:
- staticinlinefloat radians(double degrees) { return degrees * M_PI/ 180.f;
- }
主要代码如下:
原文 http://www.lvesli.com/?p=339
- - (void)drawRect:(CGRect)rect {
- CGContextRef context=UIGraphicsGetCurrentContext();
- //设置半径
- CGFloat radius=130.f;
- if (self.circularRingRadius==0) {
- self.circularRingRadius=54.f;
- }
- CGFloat intRadius=radius-self.circularRingRadius;
- //设置圆心的坐标
- CGFloat centerX=self.bounds.size.width/2.f;
- CGFloat centerY=self.bounds.size.height/2.f;
- //设置起始角度
- CGFloat pieStart=90.f;
- //设置旋转方向
- int clockwise=0; //1: 顺时针 ; 0:逆时针
- //画扇形
- if(allCount == 0){ //无资产
- CGContextSetFillColorWithColor(context, [HEXCOLOR(0xefeff4) CGColor]);
- CGContextMoveToPoint(context, centerX, centerY);
- CGContextAddArc(context, centerX, centerY, radius,radians(0), radians(360), clockwise);
- CGContextClosePath(context);
- CGContextFillPath(context);
- }else{
- for (int i=0; i<self.degreeArray.count; i++) {
- CGFloat end=pieStart+[self.degreeArray[i] doubleValue];
- if (self.isShowSeperate) {
- if(i%2==0){ //分割线
- UIColor *fillColor=self.colorArray[(int)(i/2)];
- CGContextSetFillColorWithColor(context, [fillColor CGColor]);
- }else{
- CGContextSetFillColorWithColor(context, [HEXCOLOR(0xefeff4) CGColor]);
- }
- }else{
- CGContextSetFillColorWithColor(context, [self.colorArray[i] CGColor]);
- }
- NSLog(@"%f",radians(end));
- CGContextMoveToPoint(context, centerX, centerY);
- CGContextAddArc(context, centerX, centerY, radius,radians(pieStart), radians(end), clockwise);
- CGContextClosePath(context);
- CGContextFillPath(context);
- pieStart+=[self.degreeArray[i] doubleValue];
- }
- }
- //画内圆
- CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]);
- CGContextMoveToPoint(context, centerX, centerY);
- CGContextAddArc(context, centerX, centerY, intRadius, 0, radians(360.f), 0);
- CGContextClosePath(context);
- CGContextFillPath(context);
- }
来源: http://www.phpxs.com/code/1004027/