IOS 繪製圓餅圖 簡單實現的代碼有注釋,ios
今天為大家帶來IOS 繪圖中圓餅的實現
.h檔案
#import <UIKit/UIKit.h>
@interface ZXCircle : UIView
@end
.m檔案
#import "ZXCircle.h"
@implementation ZXCircle
-(void)drawRect:(CGRect)rect{
CGFloat w = self.bounds.size.width;
CGFloat h = self.bounds.size.height;
//資料數組
NSArray *array = @[@1,@2,@3,@4,@5,@6,@7,@8,@9,@10];
//顏色數組
NSArray *colorArray = @[[UIColor redColor], [UIColor greenColor], [UIColor yellowColor],[UIColor cyanColor],[UIColor blueColor],[UIColor lightGrayColor],[UIColor grayColor],[UIColor darkGrayColor],[UIColor magentaColor],[UIColor orangeColor]];
//下面這個迴圈是為了假如只有幾種顏色 ,但是資料非常多的情況下 ,迴圈使用顏色的演算法
//建立的顏色數組
NSMutableArray * colorArr=[NSMutableArray new];
//這個迴圈是 只顯示顏色數組中前三個的顏色,%後面的數 是根據你的顏色數組中有多少顏色
for (int i=0; i<array.count; i++) {
[colorArr addObject:colorArray[i%10]];
}
CGContextRef ctx =UIGraphicsGetCurrentContext();
//中心點
CGPoint center = CGPointMake(w * 0.5, h * 0.5);
//半徑
CGFloat radius = w * 0.3 - 5;
//起點角度
CGFloat startA = 0;
//終點角度
CGFloat endA =M_PI;
//掃過角度範圍
CGFloat angle = 0;
for (int i = 0; i < array.count; i ++) {
//這句話是為了畫完其中一個之後第二個的起點就是第一個的終點,這裡面M_PI代表的是180度 55這個數值是資料來源的總和
startA = endA;
angle = [array[i] integerValue] / 55 * M_PI * 2;
endA = startA + angle;
//弧形路徑
//clockwise: 是否是按照時鐘的方向旋轉(是否順時針)
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
//串連中心, 構成扇形
[path addLineToPoint:center];
//填充顏色
[(UIColor *)colorArr[i] set];
CGContextAddPath(ctx, path.CGPath);
// 將上下文渲染到視圖
CGContextFillPath(ctx);
}
}
@end
如下: 請大家鑒賞這個非常簡單的圓餅圖 ,希望對你們以後的開發有所協助!!謝謝!!