这次绘制一个可随机变换的饼图
![这里写图片描述](https://img-blog.csdn.net/20170708114941187?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZ2V6aTA2MzA=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
新建一个UIView — PieView
在 PieView.m 写入
-(NSArray*)arrRandom
{
int totoal = 100;
NSMutableArray * arrM = [NSMutableArray array];
int temp = 0;
for (int i =0; i < arc4random_uniform(10) + 1; i++) {
temp = arc4random_uniform(totoal) + 1;
[arrM addObject:@(temp)];
if (temp == totoal) {
break;
}
totoal -= temp;
}
if (totoal) {
[arrM addObject:@(totoal)];
}
return arrM;
}
- (void)drawRect:(CGRect)rect {
NSArray * arr = [self arrRandom];
CGFloat radius = rect.size.width * 0.5;
CGPoint center = CGPointMake(radius, radius);
CGFloat startA = 0;
CGFloat endA = 0;
CGFloat angle = 0;
for (int i = 0; i < arr.count; i++) {
startA = endA;
angle = [arr[i] integerValue] / 100.0 * M_PI * 2;
endA = startA + angle;
UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
[path addLineToPoint:center];
[[self colorRandom] set];
[path fill];
}
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self setNeedsDisplay];
}
-(UIColor*)colorRandom
{
CGFloat r = arc4random_uniform(256) / 255.0;
CGFloat g = arc4random_uniform(256) / 255.0;
CGFloat b = arc4random_uniform(256) / 255.0;
return [UIColor colorWithRed:r green:g blue:b alpha:1];
}