首页 > 代码库 > 图表-折线图的实现

图表-折线图的实现

1、画坐标系

  使用CAShapeLayer画坐标系的每一根虚线:

  CAShapeLayer *shapeLayer = [CAShapeLayer layer];

      [shapeLayer setBounds:self.bounds];

      [shapeLayer setPosition:CGPointMake(CGRectGetWidth(self.frame) / 2, CGRectGetHeight(self.frame))];

      [shapeLayer setFillColor:[UIColor clearColor].CGColor];

      //  设置虚线颜色为blackColor

      [shapeLayer setStrokeColor:lineColor.CGColor];

      //  设置虚线宽度

      [shapeLayer setLineWidth:CGRectGetHeight(self.frame)];

      [shapeLayer setLineJoin:kCALineJoinMiter];

      //  设置线宽,线间距

      [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];

      //  设置路径

      CGMutablePathRef path = CGPathCreateMutable();

      CGPathMoveToPoint(path, NULL, 0, 0);

      CGPathAddLineToPoint(path, NULL, CGRectGetWidth(self.frame), 0);

      [shapeLayer setPath:path];

      CGPathRelease(path);

      //  把绘制好的虚线添加上来

      [self.layer addSublayer:shapeLayer];

2、画点连线

  根据数据源中的数据计算每个点在当前图表视图的的坐标位置,使用UIBezierPath设置路径并使用CAShapeLayer连点成线:

  for (NSInteger i = 0; i < self.dataArr.count; i++) {

          NSArray *array = self.dataArr[i];

          UIBezierPath *path = [UIBezierPath bezierPath];

          for (NSInteger i = 0; i < array.count; i++) {

              ChartModel *chart = [array objectAtIndex:i];

              CGPoint point = [self getPointWithChart:chart];

              if (i == 0) {

                  [path moveToPoint:point];

              }else {

                  [path addLineToPoint:point];

              }

          }

        CAShapeLayer *pathLayer = [CAShapeLayer layer];

        pathLayer.frame = CGRectMake(0, 0, _kWidth, _kHeight);

        pathLayer.path = path.CGPath;

        pathLayer.strokeColor = ((UIColor *)[self.colorArr objectAtIndex:i]).CGColor;

        pathLayer.fillColor = nil;

        pathLayer.lineWidth = 1.5;

        pathLayer.lineJoin = kCALineJoinRound;

        [self.layer addSublayer:pathLayer];

    }

  示例:

  技术分享

  github地址:https://github.com/lionskl/KLChartView.git  

图表-折线图的实现