iOS 繪制餅圖代碼

繪制餅圖的原理很簡單,首先繪制扇形,然后在中央添加一個圓形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;
}
主要代碼如下:
- (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);
}
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!