运行效果:

7、画饼图
方法1:
- (void)drawRect:(CGRect)rect {
NSArray *dataArray = @[@25,@25,@50];
// 画弧
CGPoint center = CGPointMake(rect.size.width * 0.5, rect.size.height * 0.5);
// 半径
CGFloat radius = rect.size.width * 0.5 - 10;
CGFloat startA = 0;
CGFloat angle = 0;
CGFloat endA = 0;
for (NSNumber *num in dataArray) {
startA = endA;
// 遍历出第一个对象25,angle =25/100 *2π,即angle = π/2,所以为1/4圆,
angle = num.intValue / 100.0 * M_PI * 2;
// 截至角度= 开始的角度+ 遍历出的对象所占整个圆形的角度
endA = startA + angle;
// 顺势针画贝塞尔曲线
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
// 设置随机颜色
[[self randomColor] set];
// 添加一根线到圆心
[path addLineToPoint:center];
// 填充路径
[path fill];
// 描边路径
// [path stroke];
}
}
/**
生成随机颜色
@return UIColor
*/
-(UIColor *)randomColor{
CGFloat redLevel = rand() / (float) RAND_MAX;
CGFloat greenLevel = rand() / (float) RAND_MAX;
CGFloat blueLevel = rand() / (float) RAND_MAX;
return [UIColor colorWithRed: redLevel green: greenLevel blue: blueLevel alpha: 1.0];
}
运行效果:

方法二:
- (void)drawRect:(CGRect)rect {
CGPoint center = CGPointMake(self.bounds.size.width * 0.5, self.bounds.size.height * .5);
CGFloat radius = self.bounds.size.width * 0.5 - 10;
CGFloat startA = 0;
CGFloat endA = 25 / 100.0 * M_PI * 2;
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
[[UIColor redColor] set];
//添加一根线到圆心
[path addLineToPoint:center];
[path fill];
//第二个扇形
startA = endA;
CGFloat angle = 25 / 100.0 * M_PI * 2;
endA = startA + angle;
UIBezierPath *path2 = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
[[UIColor greenColor] set];
//添加一根线到圆心
[path2 addLineToPoint:center];
[path2 fill];
startA = endA;
angle = 50 / 100.0 * M_PI * 2;
endA = startA + angle;
UIBezierPath *path3 = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
[[UIColor blueColor] set];
//添加一根线到圆心
[path3 addLineToPoint:center];
[path3 fill];
}
/**
生成随机颜色
@return UIColor
*/
-(UIColor *)randomColor{
CGFloat redLevel = rand() / (float) RAND_MAX;
CGFloat greenLevel = rand() / (float) RAND_MAX;
CGFloat blueLevel = rand() / (float) RAND_MAX;
return [UIColor colorWithRed: redLevel green: greenLevel blue: blueLevel alpha: 1.0];
}










