iOS-一个带可滑动指针的折线图(类似微信指数小程序)

  在开发工作中,产品同学要求下个版本要做个数据统计的功能,其中需要显示图表(我们产品同学借鉴的是微信指数的折线图形式),于是为了应付接下来的开发工作,我便写了个小demo,在这里记录下来供大家参考讨论。最终运行效果如下:
QQ20180504-172328-HD.gif

  水印请忽略,谁让我穷呢。
  废话不多说开始上代码了。首先创建一个chartView

@interface CYXLineChartView : UIView
/*y值列表*/
@property (nonatomic,strong) NSArray *yValues;
/*画线开始*/
-(void)drawChartWithMaxYValue:(CGFloat)maxYValue;
@end

定义一个画线的方法,根据最大值画线实现为:

-(void)drawChartWithMaxYValue:(CGFloat)maxYValue{
    if (maxYValue<=0||[self.yValues count]==0) {
        return;
    }
    _maxYValue = maxYValue;
    NSArray *layers = [self.layer.sublayers mutableCopy];
    for (CAShapeLayer *layer in layers) {
        [layer removeFromSuperlayer];
    }
    
    //画三条线
    [self drawXYLine];
    //添加y轴三个label
    [self drawYLabelsWithMaxYValue:maxYValue];
    //画X轴刻度和label
    [self drawXLineAndLabels];
    //画折线
    [self drawLine];
    [self addSubview:self.pointerView];
    [self addSubview:self.explainLabel];
}

首先先画三条线:

- (void)drawXYLine{
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    //y单位坐标距离
    CGFloat yUnitDistance = (CGRectGetHeight(myFrame)-kDrawMarginTop-kDrawMarginBottom)/(yCount-1);
    //从上到下
    for (int i =0; i<yCount; i++) {
        [path moveToPoint:CGPointMake(kDrawMarginLeft, yUnitDistance*i+kDrawMarginTop)];
        [path addLineToPoint:CGPointMake(CGRectGetWidth(myFrame)-kDrawMarginRight, yUnitDistance*i+kDrawMarginTop)];
    }

    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    layer.path = path.CGPath;
    layer.strokeColor = [UIColor brownColor].CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;
    layer.lineWidth = 0.5;
    [self.layer addSublayer:layer];
    self.pointerView.frame = CGRectMake(0, kDrawMarginTop, 20, CGRectGetHeight(myFrame)-kDrawMarginTop-kDrawMarginBottom+10);
}

再画y显示Label

-(void)drawYLabelsWithMaxYValue:(CGFloat)maxYValue{
    
    NSMutableArray * yValueList= [NSMutableArray new];
    //y值平均
    CGFloat yUnitValue = maxYValue/(yCount-1);
    for (int i=yCount-1; i>=0; i--) {
        [yValueList addObject:@(i*yUnitValue)];
    }
    CGFloat yUnitDistance = (CGRectGetHeight(myFrame)-kDrawMarginTop-kDrawMarginBottom)/(yCount-1);
    for (int i =0; i<yCount; i++) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, yUnitDistance*i+kDrawMarginTop, kDrawMarginLeft, 12)];
        label.centerY = yUnitDistance*i+kDrawMarginTop;
        label.textColor = [UIColor grayColor];
        label.font = [UIFont systemFontOfSize:12];
        //lbl.backgroundColor = [UIColor brownColor];
        label.textAlignment = NSTextAlignmentCenter;
        CGFloat yValue = [yValueList[i] floatValue];
        NSInteger yK = yValue/1000;
        label.text = [NSString stringWithFormat:@"%ldK",yK];
        [self addSubview:label];
    }
}

接下来画X轴刻度和显示Label

-(void)drawXLineAndLabels{
    //先计算当前月份和当前月的总天数
    [self setCurrentDaysAndMoth];
    
    NSLog(@"%02ld",_currentMonth);
    NSLog(@"%02ld",_currentMonthTotalDays);
    UIBezierPath *path = [UIBezierPath bezierPath];
    CGFloat  xUnitValue = 10;
    CGFloat  xTotalDistance = CGRectGetWidth(myFrame)-kZeroMarginLeft-kZeroMarginRight;
    CGFloat  xUnitMargin = xUnitValue/_currentMonthTotalDays *xTotalDistance;
    
    NSInteger day = 1;
    CGFloat centerX;
    for (int i=0; i<xCount; i++) {
        if (i==xCount-2) {//倒数第二个刻度
            [path moveToPoint:CGPointMake(kZeroMarginLeft+xTotalDistance-xUnitMargin, CGRectGetHeight(myFrame)-kDrawMarginBottom)];
            [path addLineToPoint:CGPointMake(kZeroMarginLeft+xTotalDistance-xUnitMargin, CGRectGetHeight(myFrame)-kDrawMarginBottom+8)];
            day = _currentMonthTotalDays-10+1;
            centerX = kZeroMarginLeft+xTotalDistance-xUnitMargin;
        }else if (i==xCount-1){//倒数第一个刻度
            [path moveToPoint:CGPointMake(kZeroMarginLeft+xTotalDistance, CGRectGetHeight(myFrame)-kDrawMarginBottom)];
            [path addLineToPoint:CGPointMake(kZeroMarginLeft+xTotalDistance, CGRectGetHeight(myFrame)-kDrawMarginBottom+8)];
            day = _currentMonthTotalDays;
            centerX = kZeroMarginLeft+xTotalDistance;
        }else{//其余刻度
            [path moveToPoint:CGPointMake(kZeroMarginLeft+i*xUnitMargin, CGRectGetHeight(myFrame)-kDrawMarginBottom)];
            [path addLineToPoint:CGPointMake(kZeroMarginLeft+i*xUnitMargin, CGRectGetHeight(myFrame)-kDrawMarginBottom+8)];
            if (i==0) {
                day = 1;
            }else{
              day = day+xUnitValue*i-1;
            }
            centerX = kZeroMarginLeft+i*xUnitMargin;
        }
        UILabel *label = [[UILabel alloc] init];
        label.textColor = [UIColor grayColor];
        label.font = [UIFont systemFontOfSize:12];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = [NSString stringWithFormat:@"%02ld-%02ld",_currentMonth,day];
        [label sizeToFit];
        label.centerX = centerX;
        label.bottom = CGRectGetHeight(myFrame)-10;
        [self addSubview:label];
    }
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    layer.path = path.CGPath;
    layer.strokeColor = [UIColor brownColor].CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;
    layer.lineWidth = 0.5;
    [self.layer addSublayer:layer];
}

再画折线

-(void)drawLine{
    if ([self.yValues count]>_currentMonthTotalDays) {
        NSLog(@"******************数据和当前月份不一致******************");
        return;
    }
    _pointList = [NSMutableArray new];
    UIBezierPath *path = [UIBezierPath bezierPath];
    
    CGFloat yTotalDistance =CGRectGetHeight(myFrame)-kDrawMarginBottom-kDrawMarginTop;
    CGFloat firstY = [[self.yValues firstObject] floatValue];
    CGPoint firstPoint =CGPointMake(kZeroMarginLeft, yTotalDistance - (firstY/_maxYValue*yTotalDistance)+kDrawMarginTop);
    [path moveToPoint:firstPoint];
    [_pointList addObject:[NSValue valueWithCGPoint:firstPoint]];
    
    CGFloat  xTotalDistance = CGRectGetWidth(myFrame)-kZeroMarginLeft-kZeroMarginRight;
    CGFloat  xUnitMargin = xTotalDistance/(_currentMonthTotalDays-1);
    for (int i =1; i<[self.yValues count]; i++) {
        CGFloat yValue =[self.yValues[i] floatValue];
        CGPoint point = CGPointMake(kZeroMarginLeft+xUnitMargin*i, yTotalDistance - (yValue/_maxYValue*yTotalDistance)+kDrawMarginTop);
        [path addLineToPoint:point];
        if (i == [self.yValues count]-1) {//刻度尺默认选择当前 日期
            self.pointerView.centerX =point.x;
            self.pointerView.maxX = point.x-self.pointerView.width/2;
        }
        [_pointList addObject:[NSValue valueWithCGPoint:point]];
    }
    [self changeExplainLabelWithCenterX:self.pointerView.centerX];
    self.pointerView.minX = kZeroMarginLeft-self.pointerView.width/2;
    self.explainLabel.top =27;
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    layer.path = path.CGPath;
    layer.strokeColor = [UIColor redColor].CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;
    layer.lineWidth = 1;
    
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = 1.5;
    pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
    pathAnimation.autoreverses = NO;
    
    [layer addAnimation:pathAnimation forKey:@"lineLayerAnimation"];
    layer.strokeEnd = 1.0;
    [self.layer addSublayer:layer];
}

最后就是解决游标问题了,创建一个游标View

@interface CYXPointerView : UIView
/*最小x*/
@property (nonatomic,assign) CGFloat minX;
/*最小x*/
@property (nonatomic,assign) CGFloat maxX;
/*当指针centerx发生变化的时候*/
@property (nonatomic,strong) void(^centerXChanged)(CGFloat centerX);
@end

游标拖拽问题,我们在-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event方法中实现

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"手指移动");
    //实现拖动
    //获取touch
    UITouch * touch = [touches anyObject];
    //获取当前点
    CGPoint curretPoint = [touch locationInView:self];
    //获取上一个点
    CGPoint prePoint = [touch previousLocationInView:self];
    //x变化
    CGFloat offsetX = curretPoint.x - prePoint.x;
    //y变化
    //CGFloat offsetY =curretPoint.y - prePoint.y;
    //相对于上一次位置的形变  make相对于原始位置
    CGPoint point = self.frame.origin;
    if (point.x+offsetX<=self.maxX&&point.x+offsetX>=self.minX) {
        //self.transform = CGAffineTransformTranslate(self.transform, offsetX, 0);
        self.left = self.left+offsetX;
    }else if (point.x+offsetX>self.maxX){
        self.left = self.maxX;
    }else if (point.x+offsetX<self.minX){
        self.left = self.minX;
    }
    self.centerXChanged(self.centerX);
}

点击图标游标的变动在CYXPointerView中实现

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //获取touch
    UITouch * touch = [touches anyObject];
    //获取当前点
    CGPoint curretPoint = [touch locationInView:self];
    NSLog(@"%f",curretPoint.x);
    if (curretPoint.x<=self.pointerView.maxX+self.pointerView.width/2&&curretPoint.x>=self.pointerView.minX+self.pointerView.width/2) {
        self.pointerView.centerX = curretPoint.x;
    }else if (curretPoint.x<=self.pointerView.maxX+self.pointerView.width/2){
        self.pointerView.left = self.pointerView.minX;
    }else if (curretPoint.x>=self.pointerView.minX+self.pointerView.width/2){
        self.pointerView.left = self.pointerView.maxX;
    }
    [self changeExplainLabelWithCenterX:self.pointerView.centerX];
}

最后解决游标显示Label显示方向的问题:

-(void)changeExplainLabelWithCenterX:(CGFloat)centerX{
    if (centerX<CGRectGetWidth(myFrame)/2) {
        self.explainLabel.left = centerX+7;
    }else{
        self.explainLabel.right = centerX-7;
    }
    for (int i=0; i<[_pointList count]; i++) {
        NSValue * value =_pointList[i];
        CGPoint point = [value CGPointValue];
        NSLog(@"%d",i);
        if (point.x>centerX&&i>0) {
            CGFloat offsetxCurrent = point.x-centerX;
            NSValue * value2 =_pointList[i-1];
            CGPoint point2 = [value2 CGPointValue];
            CGFloat offsetxNext = centerX-point2.x;
            NSLog(@"centerX:%f",centerX);
            if (offsetxCurrent<=offsetxNext) {
                NSLog(@"point:%f",point.x);
                self.explainLabel.text = [NSString stringWithFormat:@"%@",self.yValues[i]];
            }else{
                NSLog(@"point2:%f",point2.x);
                self.explainLabel.text = [NSString stringWithFormat:@"%@",self.yValues[i-1]];
            }
            break;
        }else if (point.x==centerX){
            self.explainLabel.text = [NSString stringWithFormat:@"%@",self.yValues[i]];
        }
    }
}

这样就实现了上图功能了,有问题欢迎指教。
最后付demo地址:https://github.com/SionChen/CYXLineChatDemo

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,711评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,079评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,194评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,089评论 1 286
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,197评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,306评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,338评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,119评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,541评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,846评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,014评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,694评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,322评论 3 318
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,026评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,257评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,863评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,895评论 2 351

推荐阅读更多精彩内容