首页 > 代码库 > CoreGraphics--饼状图
CoreGraphics--饼状图
//传入数据,饼状图
pieChartView.dataArr = @[@20,@50,@80,@70,@40];
- (void)drawRect:(CGRect)rect {
// Drawing code
#if 0
//贝塞尔路径
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 50, 100, 100)];
//Oval 椭圆
//线条颜色
[[UIColor redColor] setStroke];
//线条宽度
path.lineWidth = 5;
//开始画
[path stroke];
//设置填充颜色
[[UIColor yellowColor] set];
//开始填充
[path fill];
#endif
//开始
CGFloat startDegress = 0;
//结束
CGFloat endDegress = 0;
for (int i = 0; i < _dataArr.count; i++) {
//终点弧
//计算数据每个元素的值所占的百分比
endDegress += M_PI * 2 *([self.dataArr[i] floatValue]/[self sum]);
//弧 路径
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.frame.size.width/2, self.frame.size.height/2) radius:MIN(self.frame.size.width, self.frame.size.height)/2 startAngle:startDegress endAngle:endDegress clockwise:YES];
//更底层(这两句,相当于上面一句)
// CGMutablePathRef path = CGPathCreateMutable();
// CGPathAddArc(path, NULL,self.frame.size.width/2,self.frame.size.height/2, MIN(self.frame.size.width, self.frame.size.height)/2, startDegress, endDegress, YES);
//重新修改开始的弧度
//第二个弧的起点 ,是上一个弧的终点
startDegress = endDegress;
//注意:先画一个弧,然后终点-圆心 画一条线(以便能够填充,否则不能填充)
//坐标为圆心
[path addLineToPoint:CGPointMake(self.frame.size.width/2, self.frame.size.height/2)];
//线条颜色
// [[self randomColor] setStroke];
//线条宽度
// path.lineWidth = 5;
//开始画
// [path stroke];
//设置填充颜色
[[self randomColor] set];
//开始填充
[path fill];
}
}
- (UIColor *)randomColor{
return [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
}
- (void)setDataArr:(NSArray *)dataArr{
_dataArr = dataArr;
//调用drawRect刷新(再走一次上面)
[self setNeedsDisplay];
}
//获取数组中总数
#pragma mark -- 计算数组中 数据的总和
- (CGFloat)sum{
__block CGFloat sum = 0;
[self.dataArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
sum = sum + [obj floatValue];
}];
return sum;
}
CoreGraphics--饼状图