#import "CZView.h"
#define RECT_WIDTH rect.size.width
#define RECT_HEIGHT rect.size.height
@implementation CZView
- (void)drawRect:(CGRect)rect {
CGFloat width = rect.size.width;
CGFloat hight = rect.size.height;
[self demo1:width withHeight:hight]; //传递两个参数
}
//饼状图
-(void)demo1:(CGFloat )width withHeight:(CGFloat)hight{
NSArray *data = @[@30, @15, @5, @18, @2, @10, @12,@8];
//1.获取图形上下文对象
// CGContextRef ctx = UIGraphicsGetCurrentContext();
//2.创建路径
//设置圆心
CGPoint centerP = CGPointMake(width/2, hight/2);
//设置半径
CGFloat radius = MIN(width, hight)/2;
//设置起始弧度和结束弧度
CGFloat start = 0;
CGFloat end = 0;
//通过for循环绘图
for (int i = 0; i < data.count; i++)
{
end = ([data[i] floatValue]/100) * 2 * M_PI + start;
UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:centerP radius:radius startAngle:start endAngle:end clockwise:YES];
//链接圆心
[path addLineToPoint:centerP];
//设置填充颜色
[[self randomColor] set];
[path fill]; //渲染
//结束点的位置就是下一个弧的起点
start = end;
}
//3.把路径添加到上下文对象中
// CGContextAddPath(ctx, path.cgpath)
//4.渲染
}
//点击view执行重绘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//执行重绘,颜色随机变
[self setNeedsDisplay];
}
- (UIColor *) randomColor
{
//随机红绿蓝
CGFloat red = arc4random_uniform(256)/255.f; //随机值
CGFloat green = arc4random_uniform(256)/255.f;
CGFloat blue = arc4random_uniform(256)/255.f;
UIColor * color = [UIColor colorWithRed:red green:green blue:blue alpha:1.f];
return color;
}
@end