这是看的传值博客视频写的代码
首先,得到一个数组,数组里面放的是一系列数字.在这里,随机取得100以内的4个数字.
// 随机数组
- (NSArray *)arrRandom {
int total = 100;
NSMutableArray *arrM = [NSMutableArray array];
int temp = 0;
for (int i = 0; i < 3; i++) {
temp = arc4random_uniform(total);
[arrM addObject:@(temp)];
total -= temp;
}
if (temp) {
[arrM addObject:@(temp)];
}
return arrM;
}
而且,为了画出的图分辨出来,给他们添加不同的颜色
- (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];
}
开始画图
// 注意:drawRect不能手动调用,因为图形上下文我们创建不了,只能有系统帮我们创建,并且传递给我们
- (void)drawRect:(CGRect)rect {
NSArray *arr = [self arrRandom];
CGFloat radius = rect.size.width * 0.5;
CGPoint center = CGPointMake(radius, radius);
CGFloat startA = 0;
CGFloat angel = 0;
CGFloat endA = 0;
for (int i = 0; i < arr.count; i++) {
startA = endA;
angel = [arr[i] doubleValue] / 100.0 * M_PI * 2;
endA = startA + angel;
/*
* Center:圆心
* startAngle:弧度
* clockwise:YES:顺时针 NO:逆时针
*/
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
// 添加一根线到圆心
[path addLineToPoint:center];
// 给封闭的空间添加颜色
[[self colorRandom] set];
// 渲染
[path stroke];
// 填充:必须是一个封闭的路径,默认就会自动关闭路径
[path fill];
}
}
当点击的时候,改变饼状图
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 重绘:系统会先创建与 View 相关联的上下文,然后在调drawRect
[self setNeedsDisplay];
}
效果图