餅狀圖
- (void)drawRect:(CGRect)rect {
NSArray *arr = @[@20, @43, @37];
NSArray *colorArr = @[[UIColor redColor], [UIColor blueColor], [UIColor greenColor]];
CGFloat radius = self.bounds.size.width * 0.5;
CGPoint center = CGPointMake(radius, radius);
CGFloat startA = 0;
CGFloat angle = 0;
CGFloat endA = 0;
for (int i = 0; i < arr.count; i++) {
startA = endA;
angle = [arr[i] floatValue] / 100 * 2 * M_PI;
endA = startA + angle;
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
[path addLineToPoint:center];
[[self randomColor] set];
[path fill];
}
}
- (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 colorWithRed:r green:g blue:b alpha:1];
}
複製程式碼
柱狀圖
- (void)drawRect:(CGRect)rect {
NSArray *arr = [self arrRandom];
CGFloat x = 0;
CGFloat y = 0;
CGFloat w = 0;
CGFloat h = 0;
for (int i = 0; i < arr.count; i++) {
w = rect.size.width / (2 * arr.count - 1);
x = 2 * w * i;
h = [arr[i] floatValue] / 100.0 * rect.size.height;
y = rect.size.height - h;
UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(x, y, w, h)];
[[self colorRandom] set];
[path fill];
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self setNeedsDisplay];
}
- (NSArray *)arrRandom
{
int totoal = 100;
NSMutableArray *arrM = [NSMutableArray array];
int temp = 0;
for (int i = 0; i < arc4random_uniform(10) + 1; i++) {
temp = arc4random_uniform(totoal) + 1;
[arrM addObject:@(temp)];
if (temp == totoal) {
break;
}
totoal -= temp;
}
if (totoal) {
[arrM addObject:@(totoal)];
}
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];
}
複製程式碼