// 重繪
- (void)drawRect:(CGRect)rect
{
// Drawing code
CGFloat h = self.bounds.size.height;
CGFloat w = self.bounds.size.width;
// 圓心位置
CGPoint center = CGPointMake( w * 0.5, h * 0.5);
// 開始位置
CGFloat start = 0;
// 計算角度(要加點)
CGFloat angle = 0;
// 結束位置
CGFloat end= 0;
// 半徑
CGFloat radius = w * 0.5;
// 循環填充
for (NSNumber *num in _datas)
{
// 開始位置
start = end;
// 角度
angle = [num floatValue] / 100.0 *M_PI *2;
// 結束位置
end = start + angle;
// 開始拼接路徑
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius: radius startAngle:start endAngle:end clockwise:1];
// 添加點到圓心
[path addLineToPoint:center];
// 設置填充顏色
[[self randomColor] set];
// 填充
#pragma mark- 設置隨機數
- (NSArray *) randomArray:(int)count
{
NSMutableArray *arrM = [NSMutableArray array];
int total = 100;
int tem = 0;
for (int i = 0;i <count;i++)
{
tem = arc4random_uniform(100)+1;
[arrM addObject:@(tem)];
total =total - tem;
}
if(total)
}
return arrM;
}
#pragma mark- 設置重繪
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self setNeedsDisplay];
}
#pragma mark- 設置顏色隨機
- (UIColor *)randomColor
{
CGFloat r = arc4random_uniform(256) / 255.0;
CGFloat g = arc4random_uniform(256) / 255.0;
CGFloat b = arc4random_uniform(256) / 255.0;
return [[UIColor alloc] initWithRed:r green:g blue:b alpha:1];
}
// 垃圾方式
- (void)test
{
// 計算第一個扇形位置
CGFloat h = self.bounds.size.height;
CGFloat w = self.bounds.size.width;
// 圓心位置
CGPoint center = CGPointMake( w * 0.5, h * 0.5);
// 開始位置
CGFloat start1 = 0;
// 計算角度(要加點)
CGFloat angle1 = 25/100.0 * M_PI * 2;
// 結束位置
CGFloat end1 = start1 + angle1;
// 開始拼接路徑
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius: w * 0.5 startAngle:start1 endAngle:end1 clockwise:1];
// 添加點到圓心
[path addLineToPoint:center];
// 設置填充顏色
[[UIColor redColor] set];
// 填充
[path fill];
// 計算第二個扇形位置
// 開始位置
CGFloat start2 = end1;
// 計算角度(要加點)
CGFloat angle2 = 25/100.0 * M_PI * 2;
// 結束位置
CGFloat end2 = start2 + angle2;
// 開始拼接路徑
path = [UIBezierPath bezierPathWithArcCenter:center radius: w * 0.5 startAngle:start2 endAngle:end2 clockwise:1];
// 添加點到圓心
[path addLineToPoint:center];
// 設置填充顏色
[[UIColor brownColor] set];
// 填充
[path fill];
// 計算第三個扇形位置
// 開始位置
CGFloat start3 = end2;
// 計算角度(要加點)
CGFloat angle3 = 50/100.0 * M_PI * 2;
// 結束位置
CGFloat end3 = start3 + angle3;
// 開始拼接路徑
path = [UIBezierPath bezierPathWithArcCenter:center radius: w * 0.5 startAngle:start3 endAngle:end3 clockwise:1];
// 添加點到圓心
[path addLineToPoint:center];
// 設置填充顏色
[[UIColor lightGrayColor] set];
// 填充
[path fill];
}
@end