其实坚持更新真的对自己而言还算是蛮挑战的一件事情,重点在于坚持。每一次有点赞,和回复都让自己感觉非常棒。知识就是用来分享的,这就是开源越来越让人着迷的地方。
好了,来吧~Come on~
下面模拟一个数组,绘制柱状图。 完成后的样子:
柱状图.png
首先我们要获取数组中常用的一些数值,有一些常见的手法:
NSArray *arry = @[@300,@232.233,@324.324,@34,@4352,@43.0];
// 找出数组中的最大数值
CGFloat maxValue = [[arry valueForKeyPath:@"@max.floatValue"] floatValue];
// 重点在这句话上
// @”@max.floatValue”(获取最大值),
// @”@min.floatValue”(获取最小值),
// @”@avg.floatValue” (获取平均值),
// @”@count.floatValue”(获取数组大小)
// @”@sum.floatValue”(获取数组总和)
- (void)drawRect:(CGRect)rect{
NSArray *arry = @[@300,@232.233,@324.324,@34,@435,@43.0];
// 计算bar的宽度
CGFloat barW = self.bounds.size.width / (arry.count * 2 - 1);
// 找出数组中的最大数值
CGFloat maxValue = [[arry valueForKeyPath:@"@max.floatValue"] floatValue];
for (NSInteger i = 0; i < arry.count; i++) {
// 计算bar的高度
CGFloat barH = [arry[i] floatValue] * (self.bounds.size.height * BAR_HEIGHT_COEFFICIENT/ maxValue);
// 计算bar的XY
CGFloat barX = barW * i * 2;
CGFloat barY = self.bounds.size.height - barH;
// 绘制矩形
UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(barX, barY, barW, barH)];
// 给矩形添加随机色
[[self randomUIColor] set];
[path fill];
}
}
- (UIColor *)randomUIColor{
UIColor *color = [UIColor colorWithRed:(arc4random_uniform(256) / 255.0) green:(arc4random_uniform(256) / 255.0) blue:(arc4random_uniform(256) / 255.0) alpha:(arc4random_uniform(256) / 255.0)];
return color;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self setNeedsDisplay];
}
完成后的样子:
Paste_Image.png
- (void)drawRect:(CGRect)rect {
// Drawing code
NSArray *arry = @[@300,@232.233,@324.324,@34,@4352,@43.0];
// 计算数组中所有数值之和
CGFloat sumValue = [[arry valueForKeyPath:@"@sum.floatValue"] floatValue];
//设定圆弧的圆点、起始弧度
CGPoint origin = CGPointMake(150, 150);
CGFloat startAngle = 0;
CGFloat endAngle = 0;
for (NSInteger i = 0 ; i < arry.count; i++) {
// 每个数据的弧度
CGFloat angle = [arry[i] floatValue] * M_PI * 2 / sumValue;
// 计算这一段弧度的结束为止
endAngle = startAngle + angle;
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:origin radius:130 startAngle:startAngle endAngle:endAngle clockwise:YES];
// 计算下一段弧度开始的位置
startAngle = endAngle;
// 从弧边,绘制到原点。用于封闭路径,可以绘制扇形
[path addLineToPoint:origin];
// 给扇形添加随机色
[[self randomUIColor] set];
[path fill];
}
}
- (UIColor *)randomUIColor{
UIColor *color = [UIColor colorWithRed:(arc4random_uniform(256) / 255.0) green:(arc4random_uniform(256) / 255.0) blue:(arc4random_uniform(256) / 255.0) alpha:(arc4random_uniform(256) / 255.0)];
return color;
}
//触屏后重新渲染
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self setNeedsDisplay];
}
本来也想像柱状图、饼状图一样的写法,但是想想其实可以做的更形象一点。所以打算下一篇专门写一下如何用扇形来表达一个下载进度。实现后的效果如下:
rightImage.gif
Paste_Image.png
Paste_Image.png
Paste_Image.png
Paste_Image.png
Paste_Image.png
哈哈,写完这篇,下篇就开始自己绘制一个进度条拉。不知道各位是不是已经踏上回家的征程了吶?希望各位鸡年大吉~新年新祝福,说鸡不说吧~