iOS开发--简单折线图

作为一个iOS程序媛,还真是没有发文章的习惯,但是据说如果能够长期整理自己代码的心得,写成文章,那是可以证明实力的(额,算了吧,不写还没人知道很菜。。。)。

总结一下自己写过的代码小片段。

实现功能:在一个固定区域内,根据返回的几个数据做一个不带坐标的折线图,有拐点,有数据显示。

代码分两个地方写:1、自定义UIView类   2、需要显示折线图的控制器页面。

1、自定义UIView类

.h文件 其中beginX,beginY表示直线的起点,endX,endY表示直线的终点

#import

@interfaceLineRectView :UIView

@property(nonatomic,assign) int beginX;

@property(nonatomic,assign) int beginY;

@property(nonatomic,assign) int endX;

@property(nonatomic,assign) int endY;

@end

.m文件 在.m文件中需要重写drawRectangle方法

-(void)drawRect:(CGRect)rect{

//获取上下文

CGContextRefcontext =UIGraphicsGetCurrentContext();

//设置起点

CGContextMoveToPoint(context,_beginX,_beginY);

//画曲线

//第一个参数是上下文,直接穿上面获取到的。

//接下来两个参数cpx,cpy这两个是控制在哪一个点产生弧度(如果按下面那样写就没有弧度)

//最后两个参数x,y是终点的位置

CGContextAddQuadCurveToPoint(context, (_endX-_beginX)/2+_beginX, (_endY-_beginY)/2+_beginY,_endX,_endY);

//设置直线的颜色  要在获取上下文之后,否则没有效果

UIColor*color = [UIColorwhiteColor];

[colorset];

//渲染

CGContextStrokePath(context);

}

根据传入的参数,已经可以得到直线了,起点和终点坐标的参考系都是UIVIew本身。

2、显示这个折线图的页面代码

假设给出的坐标最大值为maxY,最小值为minY,因为横坐标固定大小所以不需要考虑.假设给定的高度和宽度是24 和 屛宽,给定的数据是6个

-(void)makeTheView{

int maxY =686;

int minY =600;

CGFloat unitY = (CGFloat)24/(maxY-minY);//单位高度

CGFloat unitX = (CGFloat)(kScreenWidth)/5;//单位宽度

NSArray*arr =@[@600,@600,@640,@650,@686,@665];//假设这是给出的值

for(int i =0; i

LineRectView*lineV1 = [[LineRectView alloc] initWithFrame:CGRectMake(unitX*i,86, unitX,24)];

lineV1.beginX=0;

float a = [arr[i] floatValue];

lineV1.beginY=24-(a-minY)*unitY;

lineV1.endX= unitX;

float b = [arr[i+1] floatValue];

lineV1.endY=24-(b-minY)*unitY;

lineV1.backgroundColor= [UIColor clearColor];

[self.view addSubview:lineV1];

}

for(inti =1; i

float a = [arr[i] floatValue];

//拐点

UIImageView*pointImgView = [[UIImageView alloc]initWithFrame:CGRectMake(unitX*i-2,24-(a-minY)*unitY+86-2,4,4)];

pointImgView.backgroundColor= [UIColor whiteColor];

pointImgView.layer.cornerRadius=2;

[pointImgView.layer masksToBounds];

[self.view addSubview:pointImgView];

//显示数据的lable

UILabel*pointLab = [[UILabel alloc]initWithFrame:CGRectMake(unitX*i-10,24-(a-minY)*unitY+86+2,20,12)];

pointLab.font= [UIFontsystem FontOfSize:10];

pointLab.backgroundColor= [UIColorclearColor];

pointLab.textColor=[UIColor blackColor];

pointLab.text= [NSString stringWithFormat:@"%@",arr[i]];

[self.view addSubview:pointLab];

}

}

效果如下图


iOS开发--简单折线图_第1张图片

适当修改坐标后可以是这样


iOS开发--简单折线图_第2张图片

嗯,就是这样啦~

你可能感兴趣的:(iOS开发--简单折线图)