项目涉及知识之折线绘制

2017-08-01  本文已影响0人  狗娃_

大概需求:

两条折线图。
实线:数据是有值则画线,值为0时则跳过,直到下一个点有值;
虚线:间隔7天有值,值为0时则跳过,直到下一个点有值。
日期:当前日期居中,滑动折线图时,日期跟着滑动。
滑动效果:以实线中两个有值点的距离作为一个pageSize,滑动回弹。

设计图:

设计图1.png 设计图2.png

基础知识:

1.实线的绘制方式:

    CGContextRef context = UIGraphicsGetCurrentContext(); // 获取图形上下文环境
    CGContextSetLineWidth(context, _reallineWidth);  // 设置线宽
    CGContextSetLineJoin(context, kCGLineJoinRound);// 设置线条的转角的样式
    CGContextSetLineCap(context, kCGLineCapRound);// 设置图形环境中的画线的端点样式
    CGContextMoveToPoint(context, initialPoint.x, initialPoint.y); // 移动到初始点
    CGContextAddLineToPoint(context, obj.realline_x, obj.realline_y) 
    CGContextStrokePath(context); // 绘制

2.虚线的绘制方式

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, _dashlineWidth);
    [_dashlineColor set];
    CGFloat lengths[] = {4,4}; 
    CGContextSetLineDash(context, 0, lengths, 2); // 设置虚线模式
    CGPoint initialPoint = CGPointMake(firstPoint.dashline_x, firstPoint.dashline_y);
    CGContextMoveToPoint(context, initialPoint.x, initialPoint.y); 
    CGContextStrokePath(context);

3.日期(CATextLayer)

    CATextLayer *dateLayer = [CATextLayer layer];
    dateLayer.size = CGSizeMake(kLTLineViewDateWidth, kLTLineViewDateHeight);
    dateLayer.center = CGPointMake(obj.date_x, obj.date_y);
    dateLayer.alignmentMode = kCAAlignmentCenter;
    dateLayer.font = (__bridge CFTypeRef)(_dateFont);
    dateLayer.fontSize = -_dateFont.pointSize;
    dateLayer.string = obj.date;
    dateLayer.foregroundColor = _dateColor.CGColor;
    dateLayer.contentsScale = [UIScreen mainScreen].scale;
    [self.layer addSublayer:dateLayer];

4.Scrollview滑动回弹

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    // scroll自定义page回弹size
    CGFloat kMaxIndex = (self.lineScollView.contentSize.width-kScreenWidth)/(kLTLineViewDateSpace+kLTLineViewDateWidth);
    CGFloat targetX = scrollView.contentOffset.x + velocity.x * (kLTLineViewDateSpace+kLTLineViewDateWidth);
    CGFloat targetIndex = round(targetX / (kLTLineViewDateSpace+kLTLineViewDateWidth));
    if (targetIndex < 0)
        targetIndex = 0;
    if (targetIndex > kMaxIndex)
        targetIndex = kMaxIndex;
    targetContentOffset->x = targetIndex * (kLTLineViewDateSpace+kLTLineViewDateWidth);
}

具体实现:

先看看结构示例:

结构示例.png
代码地址:
https://github.com/Cherishforever/LTLineView
上一篇下一篇

猜你喜欢

热点阅读