IOS 自定义折线图[OC]

swift版:https://www.jianshu.com/p/f581194cb02c

预览

折线图

变量初始化

//内边距
static CGFloat borderX = 40;
static CGFloat borderY = 20;
//x和y的个数
//x = 4: 2014,2015,2016,2017
//y = 6: 0,500,100,1500,2000,2500
static CGFloat x = 4;
static CGFloat y = 6;
//x和y每个单位代表的值
static CGFloat yValue = 500;
static CGFloat xValue = 1;
//x和y的起始值
static CGFloat yStart = 0;
static CGFloat xStart = 2014;
//x和y的单位长度
CGFloat widthX;
CGFloat heightY;

构造函数

-(instancetype)initWithArrayAndFrame:(NSArray *)array andFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        self.array = array;
        //计算单位长度
        widthX = (self.frame.size.width-borderX*2)/x;
        heightY = (self.frame.size.height-borderY*2)/y;
        //画x轴的label:2014,2015...
        [self drawX];
        //画y轴的label:0,500,1000...
        [self drawY];
        //画折线
        [self drawLine];
    }
    return self;
}

画坐标轴,虚线,和数据点

-(void)drawRect:(CGRect)rect{
   //画坐标轴
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
    CGContextSetLineWidth(context, 1);
    CGContextMoveToPoint(context, borderX, borderY);
    CGContextAddLineToPoint(context, borderX, rect.size.height-borderY);
    CGContextAddLineToPoint(context, rect.size.width-borderX, rect.size.height-borderY);
    CGContextStrokePath(context);
    //画y轴的分割虚线
    CGContextRef context2 = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor lightGrayColor].CGColor);
    CGContextSetLineWidth(context2, 1);
    for (int i=1; i

写X轴Y轴的数字

-(void)drawX{
    for (int i=0; i

画折线

-(void)drawLine{

    float yTotalValue = yStart + yValue*y;
    float height = self.frame.size.height - borderY*2;
    float pointy = self.frame.size.height - [self.array[0] floatValue]/yTotalValue*height - borderY;
    //在第一个点下方写数值
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(widthX/2+borderX, pointy, 50, 20)];
    label.text = [NSString stringWithFormat:@"%ld",[self.array[0] integerValue]];
    label.font = [UIFont systemFontOfSize:10];
    [self addSubview:label];
    //贝塞尔曲线设置起始点
    UIBezierPath *linePath = [UIBezierPath bezierPath];
    [linePath moveToPoint:CGPointMake(widthX/2+borderX, pointy)];
    //开始画折线和后续的数值
    for (int i=1; i

使用

NSArray *array = @[@(1342),@(2123),@(1654),@(1795)];
    ChartView *cv = [[ChartView alloc]initWithArrayAndFrame:array andFrame:CGRectMake(0, 70, 320, 250)];
    [self.view addSubview:cv];

你可能感兴趣的:(IOS 自定义折线图[OC])