iOS折线图绘制与PNChart源码

PNChart

去年项目中用到了折线图,当时因为项目赶的紧,于是下载了GitHub上排行前几名的图表框架,看一下哪一个与需求最符,最后选择了PNChart(个人感觉当初的选择还是很正确的,因为框架只能满足一些基本功能,其他的滑动、触摸、悬浮框,交集点都是需要自己改框架的,PNChart里面的代码还是挺简洁的),直到年后过了这么长时间稍微闲下来才决定看一看里面具体的实现方法。

首先PNChart无论用什么初始化方法在内部全部调用了setupDefaultValues,在这个方法里面初始化了一堆变量,同时初始化了上下左右四个边距为25.当调用setChartData,首先初始化了数组,同时设置了CAShapeLayer的一些属性,然后调用了prepareYLabelsWithData方法。

prepareYLabelsWithData方法主要是为了找出Y轴上的最大值与最小值,并且如果_showGenYLabels为真,那么调用setYLabels方法。setYLabels方法主要是用来设置Y轴上的Label的frame,同时给它赋值。当上面的步骤走完之后调用setNeedsDisplay,系统会调用drawRect方法,如果isShowCoordinateAxis为YES,即如果显示坐标轴,那么先画坐标轴,画坐标轴的的时候先画的是Y轴,然后才画X轴,注意起点和画Y轴的时候这个起点跟_chartMarginBottom有关,要注意它是可以更改的,后面又画了Y轴和X轴的箭头。

同时如果showLabel为YES,那么会画X轴和Y轴上的小突起(即每一步的突出的那个点),如果xUnit和yUnit是有值的,那么会在X轴和Y轴旁边画一个Label并赋值,如果showYGridLines为YES,即网格线显示,那么,但是在画网格线要注意一个问题如果_showLabel为YES,那么网格线的起点不是靠着最左边的,会有默认值10,当为NO是,默认值为0,所以可以在代码里面更改。同时在这一块还控制了网格线是虚线还是实现,当网格线默认为虚线,可以更改为实线,只要把那里面的数值更改一下(简单来说在drawRect方法里面画了坐标轴和坐标轴的箭头以及上面的小突起,还有旁边的Label还有网格线)

当调用strokeChart的时候,首先在方法内部调用了一个方法,这个方法的主要作用是根据折线的类型来画折线(先算出X轴和Y轴的位置,然后画相应的线),其实这个折线是默认有动画的,可以设置displayAnimated属性为NO来让不让有动画

自己绘制简单的折线图

1.首先设置变量的默认值

-(void)createDefaultValue
{
    _nowIndex = 1;
    _dataArray = [NSMutableArray array];
    _lineLayer = [CAShapeLayer layer];
    [_lineLayer setLineCap:kCALineCapRound];
    [_lineLayer setLineJoin:kCALineJoinRound];
    [_lineLayer setLineWidth:1];
    [_lineLayer setStrokeColor:[UIColor blackColor].CGColor];
    [_lineLayer setFillColor:[UIColor clearColor].CGColor];
    
    _maskLayer = [CAShapeLayer layer];
    _gradientLayer = [CAGradientLayer layer];
    _gradientLayer.frame = self.bounds;//必须设置渐变涂层的frame,不然渐变涂层出不来
    
    _gradientLayer.colors = @[(__bridge id)[UIColor redColor].CGColor,(__bridge id)[UIColor whiteColor].CGColor];
    _gradientLayer.startPoint = CGPointMake(0, 0);
    _gradientLayer.endPoint = CGPointMake(0, 1);

    for (int i = 0; i < totalCount; i ++) {
        CGFloat lineW = (self.width - LeftDistance*2)/totalCount;
        CGFloat linex = LeftDistance + lineW/2.0 + i*lineW;
        NSInteger w = (self.height - LeftDistance*2 - 60);
        CGFloat liney = arc4random()% w;
        CGPoint point = CGPointMake(linex, liney);
        [_dataArray addObject:[NSValue valueWithCGPoint:point]];
    }
}

然后绘制折线图的边框和虚线

-(void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    [[UIColor blackColor]setStroke];
    CGContextSetLineCap(context, kCGLineCapSquare);
    CGContextSetLineJoin(context, kCGLineJoinRound);
    CGContextSetLineWidth(context, 1);
    CGRect lineRect = CGRectMake(LeftDistance, LeftDistance, self.width - LeftDistance*2, self.height - LeftDistance*2);
    CGContextAddRect(context, lineRect);
    CGContextStrokePath(context);
    
    CGFloat lineW = (self.width - LeftDistance*2)/LineCount;
    CGFloat lineH = (self.height - LeftDistance*2)/LineCount;
    
    for (int i = 0; i < LineCount; i ++) {
        CGFloat dash[] = {10,2};
        CGContextSetLineDash(context, 0, dash, 2);
        CGContextMoveToPoint(context, LeftDistance, LeftDistance + (i+1)*lineH);
        CGContextAddLineToPoint(context, self.width - LeftDistance , LeftDistance + (i+1)*lineH);
        CGContextStrokePath(context);
    }
    
    for (int i = 0; i < LineCount; i ++) {
        CGFloat dash[] = {10,2};//当把2改为0的时候其实虚线就变为了实线
        CGContextSetLineDash(context, 0, dash, 2);
        CGContextMoveToPoint(context, LeftDistance + (i +1)*lineW, LeftDistance );
        CGContextAddLineToPoint(context, LeftDistance + (i +1)*lineW, self.height - LeftDistance);
        CGContextStrokePath(context);
    }
}

最后根据数据和类型绘制不同的折线

-(void)strokeLinePath
{
    if (_type == lineAnimation || _type == lineAnimationNone || _type == lineFillAnimationNone) {
        UIBezierPath *path = [UIBezierPath bezierPath];
        for (int i = 0; i < _dataArray.count; i ++) {
            CGPoint point = [_dataArray[i] CGPointValue];
            if(i == 0)
            {
                [path moveToPoint:point];
            }else
            {
                [path addLineToPoint:point];
            }
        }
        _lineLayer.path = path.CGPath;
        [self.layer addSublayer:_lineLayer];
        //简单的折线图到这里已经绘制完毕
        if (_type == lineAnimation) {
            CABasicAnimation *animate = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
            animate.fromValue = @0;
            animate.toValue = @1;
            animate.duration = 4;
            [_lineLayer addAnimation:animate forKey:@"strokeEnd"];
        }//给折线图添加动画
        if (_type == lineFillAnimationNone) {
            CGPoint lastPoint = [_dataArray[totalCount -1] CGPointValue];
            CGPoint firstPoint = [_dataArray[0] CGPointValue];
            [path addLineToPoint:CGPointMake(lastPoint.x, self.height - LeftDistance)];
            [path addLineToPoint:CGPointMake(LeftDistance, self.height - LeftDistance)];
            [path addLineToPoint:firstPoint];
            _maskLayer.path = path.CGPath;
            _gradientLayer.mask = _maskLayer; //最关键是这一句,设置渐变涂层的mask
            [self.layer addSublayer:_gradientLayer];
            
            
            //其实这一种还有令一种实现,即:
//            CGPoint lastPoint = [_dataArray[totalCount -1] CGPointValue];
//            CGPoint firstPoint = [_dataArray[0] CGPointValue];
//            [path addLineToPoint:CGPointMake(lastPoint.x, self.height - LeftDistance*2)];
//            [path addLineToPoint:CGPointMake(LeftDistance, self.height - LeftDistance*2)];
//            [path addLineToPoint:firstPoint];
//            UIBezierPath *fillPath = [UIBezierPath bezierPathWithCGPath:path.CGPath];
//            CAShapeLayer *fillLayer = [CAShapeLayer layer];
//            [fillLayer setLineCap:kCALineCapRound];
//            [fillLayer setLineJoin:kCALineJoinRound];
//            [fillLayer setLineWidth:1];
//            [fillLayer setStrokeColor:[UIColor clearColor].CGColor];
//            [fillLayer setFillColor:[UIColor orangeColor].CGColor];
//            fillLayer.path = fillPath.CGPath;
//            [self.layer addSublayer:fillLayer];
        } //带渐变实心色的折线图
    }else
    {
    _timer = [NSTimer timerWithTimeInterval:3.0/_dataArray.count repeats:YES block:^(NSTimer * _Nonnull timer) {
        UIBezierPath *path = [UIBezierPath bezierPath];
        CGPoint firstPoint = [_dataArray[0] CGPointValue];
        CGPoint nextPoint = [_dataArray[_nowIndex] CGPointValue];
        [path moveToPoint:firstPoint];
        for (int i = 0; i < _dataArray.count; i ++) {
            if (_nowIndex < i) {
                break;
            }
            if (_nowIndex != 0) {
                CGPoint point = [_dataArray[i] CGPointValue];
                [path addLineToPoint:point];
            }
        }
        
        _lineLayer.path = path.CGPath;
        [self.layer addSublayer:_lineLayer];
        
        [path addLineToPoint:CGPointMake(nextPoint.x, self.height -LeftDistance)];
        [path addLineToPoint:CGPointMake(firstPoint.x, self.height - LeftDistance)];
        [path addLineToPoint:firstPoint];
        
        _maskLayer.path = path.CGPath;
        _gradientLayer.mask = _maskLayer;
        [self.layer addSublayer:_gradientLayer];
        
        _nowIndex ++ ;
        if (_nowIndex == _dataArray.count) {
            [_timer invalidate];
        }
    }];
        [[NSRunLoop currentRunLoop]addTimer:_timer forMode:NSDefaultRunLoopMode];
    }//渐变实心的折线图带动画
    
}

实现的效果:
(1)折线图没有动画(即lineAnimationNone)

屏幕快照 2017-04-05 14.18.13.png

(2)折线图有动画

33655E7FE97C9A071DA5F40741180744.png

(3)折线图带渐变色不带动画(即lineFillAnimationNone)

屏幕快照 2017-04-05 14.21.25.png

(4)折线图实心带渐变色和动画(即lineFillAnimation)

C4A05C3479E982F4131696E149564AD1.png

小结:这是自己写的一个简单折线图的不同类型,但是最后一个折线图带渐变色和动画的是有问题的,因为当数据源不同的时候这个动画的时间也会不一样,我当时取巧用一个固定的时间去除以数据源,但是出来的效果还是跟原先没多少区别,所以最后一种类型还是只是作为参考,希望各位有什么好的办法实现可以告诉我。

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

推荐阅读更多精彩内容

  • 说明: 已将折线图封装到了一个UIView子类中,并提供了相应的接口。若你遇到相应的需求可以直接将文件拖到项目中,...
    AHLQ阅读 7,230评论 5 47
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,612评论 4 59
  • 折线图这个东西在我这家公司之前很少触及,因为我之前很讨厌贝塞尔曲线,虽然简历上写着熟悉贝塞尔曲线,会用它做各种...
    希望的翅膀阅读 789评论 6 5
  • “业精于勤,荒于嬉。行成于思,毁于随。”——【唐】韩愈《进学解》 第二天早晨王语嫣睡到自然醒,或许是真累了...
    留子儿阅读 227评论 0 0
  • 周二是不是有一种魔力 也可能只是周一的延续 此时此刻,我坐在电脑前,一片茫然,我该做什么,我是谁,我在哪儿,我为什...
    以为佚名是人名阅读 168评论 0 0