iOS繪製折線圖

折線圖的繪製網上有很多不錯的三方可以借鑑,譬如# PNChart、# SCChart等等,如果這些適合你的項目的話,不妨就使用這類的三方。但要是爲了適用於你的項目時,你需要改很多的東西,實現起來比較麻煩的話,建議自己動手寫一下,折線圖的實現起來,也不是特別的難,無非就是CAShapeLayer、UIBezierPath兩個類的結合使用,如果你還想加點動畫的話,就多一個CABasicAnimation這個類的的使用而已。就像提到的這兩個三方,如何實現中間有某些點沒有值,這個就需要動源碼了,改一些東西,感覺找的太麻煩,於是就自己寫了。
首先看一下Demo的實現效果:

效果圖.gif

自己的項目需要實現單頁展示的少數據量功能,也需要展示多數據量的長頁面拖拽功能。
下面是實現思路:

1.繪製座標軸

繪製座標軸方法.png
  - (void)drawRect:(CGRect)rect {
    /*******畫出座標軸********/
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2.0);
    CGContextSetRGBStrokeColor(context, 1, 0, 0, 1);
    CGContextMoveToPoint(context, bounceX, 0);
    CGContextAddLineToPoint(context, bounceX, rect.size.height - bounceY);
    CGContextAddLineToPoint(context,rect.size.width , rect.size.height - bounceY);
    CGContextStrokePath(context);
}

由於我的項目不需要這個東西,我就給註釋了。

2.繪製X、Y軸內容

  #pragma mark --- 創建x軸的數據
- (void)createLabelX{
self.gradientBackgroundView =[[UIScrollView alloc] initWithFrame:CGRectMake(bounceX, 0, self.bounds.size.width - bounceX, self.bounds.size.height)];
CGFloat widthlable = (self.frame.size.width - bounceX)/7;
self.gradientBackgroundView.contentSize = CGSizeMake(widthlable*self.horizontalDateArray.count, self.bounds.size.height);
[self addSubview:self.gradientBackgroundView];

for (NSInteger i = 0; i < self.horizontalDateArray.count; i++) {
    CGFloat heightlable = bounceY;
    UILabel * LabelMonth = [[UILabel alloc]initWithFrame:CGRectMake(widthlable * i , self.gradientBackgroundView.frame.size.height - heightlable+bounceX/2.0, widthlable, heightlable-bounceX/2.0)];
    LabelMonth.textAlignment = NSTextAlignmentCenter;
    LabelMonth.tag = 1000 + I;
    LabelMonth.textColor = [UIColor colorWithRed:166/255.0 green:166/255.0 blue:166/255.0 alpha:1];
    LabelMonth.text = self.horizontalDateArray[I];
    LabelMonth.font = [UIFont systemFontOfSize:10];
    LabelMonth.numberOfLines = 0;
    LabelMonth.lineBreakMode = 0;
    [self.gradientBackgroundView addSubview:LabelMonth];
  }
}

#pragma mark 創建y軸數據
- (void)createLabelY{
CGFloat Ydivision = self.verticalDateArray.count-1;
for (NSInteger i = 0; i < self.verticalDateArray.count ; i++) {
    UILabel * labelYdivision = [[UILabel alloc]initWithFrame:CGRectMake(0, (self.frame.size.height -  bounceY)/Ydivision *i, bounceX, bounceX/2.0)];
    labelYdivision.tag = 2000 + I;
    labelYdivision.textColor = [UIColor colorWithRed:166/255.0 green:166/255.0 blue:166/255.0 alpha:1];
    labelYdivision.text = [NSString stringWithFormat:@"%@",self.verticalDateArray[I]];
    labelYdivision.font = [UIFont systemFontOfSize:10];
    [self addSubview:labelYdivision];
  }
}

3.繪製虛線、添加點標註、添加動畫

這裏只繪製了橫向虛線,如果有縱向虛線繪製要求,方法類似。

  #pragma mark --- 傳添加虛線
  - (void)setLineDash{
    UILabel *xLabel = (UILabel*)[self viewWithTag:1000 + self.horizontalDateArray.count-1];
    for (NSInteger i = 0;i < self.verticalDateArray.count; i++ ) {
    CAShapeLayer * dashLayer = [CAShapeLayer layer];
    dashLayer.strokeColor = [UIColor colorWithRed:222/255.0 green:223/255.0 blue:224/255.0 alpha:1].CGColor;
    dashLayer.fillColor = [[UIColor clearColor] CGColor];
    dashLayer.lineWidth = 1.0;
    
    
    UILabel * label1 = (UILabel*)[self viewWithTag:2000 + I];
    
    UIBezierPath * path = [[UIBezierPath alloc]init];
    path.lineWidth = 1.0;
    UIColor * color = [UIColor whiteColor];
    [color set];
    [path moveToPoint:CGPointMake( 0, label1.frame.origin.y+bounceX/4.0)];
    [path addLineToPoint:CGPointMake(xLabel.frame.origin.x+xLabel.frame.size.width,label1.frame.origin.y+bounceX/4.0)];
    CGFloat dash[] = {2,2};
    [path setLineDash:dash count:2 phase:10];
    [path stroke];
    
    
    dashLayer.path = path.CGPath;
    dashLayer.lineDashPattern=[NSArray arrayWithObjects:[NSNumber numberWithInt:1],
                               [NSNumber numberWithInt:2],nil];
    [self.gradientBackgroundView.layer addSublayer:dashLayer];
  }
}

4.繪製折線圖

  #pragma mark 畫折線圖
  - (void)dravLine{
    CGFloat MaxY ;
    CGFloat firstdate = [[NSString stringWithFormat:@"%@",self.verticalDateArray[0]] floatValue] ;
    CGFloat lastdate = [[NSString stringWithFormat:@"%@",[self.verticalDateArray lastObject]] floatValue];
    MaxY = firstdate - lastdate;
    for(NSInteger LineNumber = 0; LineNumber < 3; LineNumber++){
    UIBezierPath * path = [[UIBezierPath alloc]init];
    path.lineWidth = 1.0;
    UIColor * color = [UIColor greenColor];
    [color set];
    UIColor * linecolors = (UIColor*)self.lineColorArray[LineNumber];
    NSArray *array = self.dataArray[LineNumber];
    //判斷是否是一個可顯示的第一個點
    BOOL isFirstPoint = NO;
    //創建折現點標記
    for (NSInteger i = 0; i< self.horizontalDateArray.count; i++) {
        UILabel * label1 = (UILabel*)[self viewWithTag:1000 + I];
        CGFloat arc =[[NSString stringWithFormat:@"%@",array[i]] floatValue];
        if (![[NSString stringWithFormat:@"%@",array[0]] isEqualToString:@"-100"]) {
            //第一個數不是空的,是可用數
            if (i==0) {
                [path moveToPoint:CGPointMake(label1.frame.origin.x+label1.frame.size.width*0.5,(MaxY -arc +lastdate) /MaxY * (self.frame.size.height - bounceY+bounceX/4.0)+2)];
            }else{
                if (![[NSString stringWithFormat:@"%@",array[i]] isEqualToString:@"-100"]) {
                    [path addLineToPoint:CGPointMake(label1.frame.origin.x+label1.frame.size.width*0.5,(MaxY -arc +lastdate) /MaxY * (self.frame.size.height - bounceY+bounceX/4.0)+2)];
                }
                
            }
        }else{
            //第一個數是空的,不可用數
            UILabel * labelX = (UILabel*)[self viewWithTag:1000 + I];
            if (![[NSString stringWithFormat:@"%@",array[i]] isEqualToString:@"-100"]&&!isFirstPoint) {
                
                [path moveToPoint:CGPointMake(labelX.frame.origin.x+labelX.frame.size.width*0.5,(MaxY -arc +lastdate) /MaxY * (self.frame.size.height - bounceY+bounceX/4.0+2))];
                isFirstPoint = YES;
            }else{
                if (![[NSString stringWithFormat:@"%@",array[i]] isEqualToString:@"-100"]&&isFirstPoint){
                    [path addLineToPoint:CGPointMake(labelX.frame.origin.x+labelX.frame.size.width*0.5,(MaxY -arc +lastdate) /MaxY * (self.frame.size.height - bounceY+bounceX/4.0)+2)];
                }
            }
            
            
        }

        //添加每個對應的點視圖
        if (![[NSString stringWithFormat:@"%@",array[i]] isEqualToString:@"-100"]) {
            UILabel *pointView = [[UILabel alloc] initWithFrame:CGRectMake(label1.frame.origin.x+label1.frame.size.width*0.5-2, (MaxY -arc +lastdate) /MaxY * (self.frame.size.height - bounceY+bounceX/4.0), 4, 4)];
            pointView.tag = 4000 * (LineNumber + 1)+ I;
            pointView.backgroundColor = linecolors;
            pointView.layer.masksToBounds = YES;
            pointView.layer.cornerRadius = 2.f;
            [self.gradientBackgroundView addSubview:pointView];
        }
        //添加折線對應點的數值label
        //            UILabel * falglabel = [[UILabel alloc]initWithFrame:CGRectMake(label1.frame.origin.x  , (MaxY -arc +lastdate) /MaxY * (self.frame.size.height - bounceY )  , 30, 15)];
        //            falglabel.tag = 3000 * (LineNumber + 1)+ I;
        //            falglabel.text = [NSString stringWithFormat:@"%.1f",arc];
        //            falglabel.font = [UIFont systemFontOfSize:8.0];
        //            falglabel.textColor = self.lineColorArray[LineNumber];
        //            [self addSubview:falglabel];
    }
    
    CAShapeLayer *lineChartLayer = [CAShapeLayer layer];
    
    lineChartLayer.path = path.CGPath;
    
    lineChartLayer.strokeColor = linecolors.CGColor;
    lineChartLayer.fillColor = [[UIColor clearColor] CGColor];
    // 默認設置路徑寬度爲0,使其在起始狀態下不顯示
    lineChartLayer.lineCap = kCALineCapRound;
    lineChartLayer.lineJoin = kCALineJoinRound;
    lineChartLayer.lineWidth = 1;
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = 2;
    pathAnimation.repeatCount = 1;
    pathAnimation.removedOnCompletion = YES;
    pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
    // 設置動畫代理,動畫結束時添加一個標籤,顯示折線終點的信息
    pathAnimation.delegate = self;
    [lineChartLayer addAnimation:pathAnimation forKey:@"strokeEnd"];
    
    [self.gradientBackgroundView.layer addSublayer:lineChartLayer];//直接添加導視圖上
    //   self.gradientBackgroundView.layer.mask = self.lineChartLayer;//添加到漸變圖層
  }
}
跳過沒有值的點.png
添加標註.png
每條線對應的意義.png

5.在自定義的View裏調用上面的所有方法

- (void)drawRect:(CGRect)rect {
    /*******畫出座標軸********/
//        CGContextRef context =  UIGraphicsGetCurrentContext();
//        CGContextSetLineWidth(context, 2.0);
//        CGContextSetRGBStrokeColor(context, 1, 0, 0, 1);
//        CGContextMoveToPoint(context, bounceX, 0);
//        CGContextAddLineToPoint(context, bounceX, rect.size.height - bounceY);
//        CGContextAddLineToPoint(context,rect.size.width , rect.size.height - bounceY);
//        CGContextStrokePath(context);
  [self createLabelX];
  [self createLabelY];
  [self setLineDash];
  [self dravLine];
  [self setLineMean];
}

6.外界調用這個控件的方法

  #pragma mark --- 繪製X、Y值 、虛線
- (void )drawLineDashWithHorizontalDateArray:(NSArray *)horizontalDateArray VerticalDateArray:(NSArray *)verticalDateArray SourceData:(NSArray *)dataArray{
  _horizontalDateArray = horizontalDateArray;
  _verticalDateArray = verticalDateArray;
  _dataArray = dataArray;

  [self setNeedsDisplay];
}
點h文件.png
點m文件.png

7.使用方法

使用方法.png

Demo鏈接# DrawLineChartDemo代碼沒做優化,有好的優化還請在github上提交一下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章