功能如图所示有三个饼状图点击时随机换颜色
绘制流程:给出三个饼状图的比例;绘制的上一个扇形的终点作为下一个扇形的起点加上占圆的比例作为角度再将颜色进行填充;点击view是进行setNeedDisplay方法重绘
具体代码:
//
// GPieView.m
// Quartz2D-饼状图
//
// Created by gaocai on 16/7/28.
// Copyright © 2016年 gaocai. All rights reserved.
//
#import "GPieView.h"
@implementation GPieView
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
NSArray *dataArray = @[@25, @25, @50];
CGPoint center = CGPointMake(self.bounds.size.width * 0.5, self.bounds.size.height * 0.5);
CGFloat radius = self.bounds.size.width * 0.5 - 10;
CGFloat start = 0;
CGFloat angle = 0;
CGFloat end = 0;
for (NSNumber *number in dataArray) {
start = end;
angle = number.intValue / 100.0 * M_PI * 2;
end = start + angle;
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:start endAngle:end clockwise:YES];
[[self randomColor] set];
//画一个线到圆心
[path addLineToPoint:center];
//所画路径闭合则形成一个扇形
[path fill];
}
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//重绘
[self setNeedsDisplay];
}
- (UIColor *)randomColor {
CGFloat r = arc4random_uniform(256) / 255.0;
CGFloat g = arc4random_uniform(256) / 255.0;
CGFloat b = arc4random_uniform(256) / 255.0;
return [UIColor colorWithHue:r saturation:g brightness:b alpha:1];
}
@end