可滑动折线图功能实现

前段日子做一个医疗的项目,需要用到可滑动刷新监测点位置,折线图,柱状图功能看了下网上的demo也没有找到特别理想的demo,便自己写了下,下面趁着午休给大家分享下可滑动的折线图实现。

1,折线功能实现,利用贝塞尔曲线连接两点之间位置实现

- (void)updatePathsArray:(NSArray *)array
{
    if ([array count] >= 2) {
        
        UIBezierPath *path = [[UIBezierPath alloc] init];
        [path moveToPoint:[[array firstObject] CGPointValue]];
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, [array count] - 1)];
        [array enumerateObjectsAtIndexes:indexSet
                                 options:0
                              usingBlock:^(NSValue *pointValue, NSUInteger idx, BOOL *stop) {
                                  [path addLineToPoint:[pointValue CGPointValue]];
                              }];
        ((CAShapeLayer *)self.layer).path = path.CGPath;
    }
    else
    {
        ((CAShapeLayer *)self.layer).path = nil;
    }
}

2,点以及点上面数字实现

- (void)curBegainPoint:(CGPoint)begain Index:(int)index Color:(UIColor *)color DataArray:(NSArray *)dataArray TextArray:(NSArray *)textArray{
    CAShapeLayer *supLayer = [CAShapeLayer layer];
    supLayer.frame = CGRectMake(begain.x - 20, begain.y - 30, 40, 40);
    //实心点
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.frame = CGRectMake(16, 26, 8, 8);
    layer.backgroundColor = color.CGColor;
    layer.cornerRadius = 4;
    layer.masksToBounds = YES;
    [supLayer addSublayer:layer];
    [self.layer addSublayer:supLayer];
    //文字
    CATextLayer *textLayer = [CATextLayer layer];
    textLayer.frame = CGRectMake(0, 10, 40, 30);
    textLayer.string = [NSString stringWithFormat:@"%.1f",[textArray[index] floatValue]];
    UIFont *font = [UIFont systemFontOfSize:10];
    textLayer.fontSize = font.pointSize;
    textLayer.foregroundColor = color.CGColor;
    textLayer.alignmentMode = kCAAlignmentCenter;
    textLayer.contentsScale = 2.0f;
    textLayer.wrapped = YES;
    [supLayer addSublayer:textLayer];
    [self drawText:[NSString stringWithFormat:@"%.1f",[textArray[index] floatValue]]];
    
}


3,点位置监听由于需要滑动所以我重写的scrollerView,blank为两点空隙,因为我其实位置之前为屏幕所以需要减去相应的blank位置,现demo在减去距离右面空隙即可,如下

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if ((scrollView.contentSize.width - kScreenWidth - self.blank - scrollView.contentOffset.x)/_blank > 0 && _blank != 0 &&  _scrollDelegate && [_scrollDelegate respondsToSelector:@selector(YXChartLineScrollDelegateIndex:)]) {
        [_scrollDelegate YXChartLineScrollDelegateIndex:(scrollView.contentSize.width - kScreenWidth - self.blank - scrollView.contentOffset.x)/_blank];
    }
}


4,相关问题

a,左右刷新问题,由于我是继承的scrollerView,所以我重写scrollerView添加的刷新,此部分相关功能下面文章再介绍

b,内存以及加载优化问题,drawRect方法会占用大量内存,因此不适合在此处使用,CAShapeLayer比CALayer加载更快,CATextLayer比UILabel加载更快这部分也在后面详细讲解


5,效果如下, demo地址


可滑动折线图功能实现_第1张图片 可滑动折线图功能实现_第2张图片

你可能感兴趣的:(iOS程序开发,折线图,滑动,刷新)