首页 热点专区 小学知识 中学知识 出国留学 考研考公
您的当前位置:首页正文

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

2024-12-20 来源:要发发知识网
  在开发工作中,产品同学要求下个版本要做个数据统计的功能,其中需要显示图表(我们产品同学借鉴的是微信指数的折线图形式),于是为了应付接下来的开发工作,我便写了个小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]];
        }
    }
}
显示全文