iOS 柱状图

来源:互联网 发布:centos netstat 编辑:程序博客网 时间:2024/06/02 04:47

柱状图其实就是画矩形,比如我们需要实现下面这个效果
这里写图片描述
画图思路:
1、根据数据源的个数来判断需要画多少个矩形(比如:25,15,30,10,20,需要画5个矩形)
2、画在柱状图我们只需要确定每一个柱状图的(x,y,width,height)
3、因为每个柱状图的宽是相同的,width =ViewWidth / (2 *array.count - 1)
4、根据宽度可以知道每个柱状图的x,x = 2 * width * i,i代表第几个
5、每个柱状图的高度需要判断柱状图的占整个View高度的多少,如果是柱状图高度为100,那么它的高度就等于View的高度,height = array[i] / 100 * Viewheight
6、每个柱状图的y值,y = ViewHeight - height

- (void)drawRect:(CGRect)rect{    //数据源    NSArray *numberArray = @[@25,@15,@30,@10,@20];    NSArray *colorArray = @[[UIColor redColor],[UIColor yellowColor],[UIColor purpleColor],[UIColor greenColor],[UIColor orangeColor]];    CGFloat x = 0;    CGFloat y = 0;    CGFloat w = 0;    CGFloat h = 0;    for (int i = 0; i < numberArray.count; i ++) {        w = rect.size.width / (2 *numberArray.count - 1);        x = 2 * w * i;        h = [numberArray[i] floatValue] / 100 * rect.size.height;        y = rect.size.height - h;        UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(x, y, w, h)];        [colorArray[i] setFill];        [path fill];    }}

最后,附上相关的demo,Git:(https://github.com/hejiasu/Drawing)

原创粉丝点击