餅狀圖
- (void)drawRect:(CGRect)rect {
// Drawing code
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 {
// Drawing code
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; // 30 40 30
for (int i = 0; i < arc4random_uniform(10) + 1; i++) {
temp = arc4random_uniform(totoal) + 1;
// 100 1~100
// 隨機出來的臨時值等于總值,直接退出循環(huán),因為已經把總數分配完畢,沒必要在分配。
[arrM addObject:@(temp)];
// 解決方式:當隨機出來的數等于總數直接退出循環(huán)。
if (temp == totoal) {
break;
}
totoal -= temp;
}
// 100 30 1~100
// 70 40 0 ~ 69 1 ~ 70
// 30 25
// 5
if (totoal) {
[arrM addObject:@(totoal)];
}
return arrM;
}
- (UIColor *)colorRandom
{
// 0 ~ 255 / 255
// OC:0 ~ 1
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];
}
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。