IOS折线图

做项目要统计商品的销售情况,美工那边给了效果图,自己就按照效果图自定义了一个ScrollView。整体效果不错,在做的过程中遇到的问题也记录一下。

现在这个还有许多优化的地方:

1.一个表中只能画一个折线

2.目前的要求最小值为0,没考虑负数的最小值

//
//  LineChartView.h
//  chart
//
//  Created by City--Online on 15/9/17.
//  Copyright  2015年 City--Online. All rights reserved.
//

#import <UIKit/UIKit.h>

//设置两点的水平间距
#define SPACING 70.0

//文本类型
typedef NS_ENUM(NSInteger, TitleType) {
    TitleForX,
    TitleForPoint
};

@class LineChartView;

@protocol LineChartDataSource <NSObject>
@required

//折点数量
-(NSInteger)numberForChart:(LineChartView *)chart;

//折点数值
-(float)chart:(LineChartView *)chart valueAtIndex:(NSInteger)index;

@optional

//X轴坐标是否有背景色
-(BOOL)chart:(LineChartView *)chart backGroundColorAtXPointIndex:(NSInteger)index;

//X 轴的标题
-(NSString *)chart:(LineChartView *)chart titleForXLabelAtIndex:(NSInteger)index;

@end

@interface LineChartView : UIScrollView
@property(nonatomic,assign)id<LineChartDataSource> dataSource;
@end
//
//  LineChartView.m
//  chart
//
//  Created by City--Online on 15/9/17.
//  Copyright  2015年 City--Online. All rights reserved.
//

#import "YZPLineChartView.h"

@interface YZPLineChartView ()
@property (nonatomic,strong) CAShapeLayer * linePath;
@property(nonatomic,assign)NSInteger maxValue; //最大值
@property(nonatomic,assign)NSInteger count;    //点数
@property(nonatomic,assign)CGFloat avgHeight;  //刻度
@end

@implementation YZPLineChartView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor=[UIColor whiteColor];
        _linePath=[CAShapeLayer layer];
        _linePath.lineCap=kCALineCapRound;
        _linePath.lineJoin=kCALineJoinBevel;
        _linePath.lineWidth=1;
        _linePath.fillColor=[UIColor clearColor].CGColor;
        self.bounces=NO;
        self.showsHorizontalScrollIndicator=NO;
        self.showsVerticalScrollIndicator=NO;
        _maxValue=1;

    }
    return self;
}
//最大值
-(NSInteger)maxValue
{
    for (int i=0; i<self.count; i++) {
        NSInteger value=[_dataSource chart:self valueAtIndex:i];
        _maxValue=value>_maxValue?value:_maxValue;
    }
    return _maxValue;
}
//点数
-(NSInteger)count
{
    return [_dataSource numberForChart:self];
}
//刻度
-(CGFloat)avgHeight
{
    CGFloat height=self.frame.size.height;
    _avgHeight=(height-40-20)/self.maxValue;
    return _avgHeight;
}

-(void)drawRect:(CGRect)rect
{
    [super drawRect:rect];

    //每次加载先删除原有图层
    int count = [self.layer.sublayers count];
    for (int i = 0; i<count; i++) {
        [self.layer.sublayers[0] removeFromSuperlayer];
    }

    //不能通过for in 删除  was mutated while being enumerated 遍历的时候不能删除
//    for (CALayer *layer in self.layer.sublayers) {
//        [layer removeFromSuperlayer];
//    }
    if (self.count<=0) {
        return;
    }

    [self.layer addSublayer:_linePath];

    self.contentSize=CGSizeMake((self.count)*SPACING, self.bounds.size.height);
    //画底部边线

    [self drawVerticalLineStartPoint:CGPointMake(0, self.bounds.size.height-40) withEndPoint:CGPointMake(self.contentSize.width, self.bounds.size.height-40) withColor:[UIColor grayColor] ];

    //画折线
    [self drawBrokenLine];

}
//画底部边线
-(void)drawBottomLine
{
    UIBezierPath *bottomLine=[UIBezierPath bezierPath];
    [bottomLine moveToPoint:CGPointMake(0, self.bounds.size.height-40)];
    [bottomLine addLineToPoint:CGPointMake(self.contentSize.width, self.bounds.size.height-40)];
    [[UIColor colorWithRed:0.902f green:0.902f blue:0.902f alpha:1.00f] setStroke];
    [bottomLine stroke];

}
//画竖线
-(void)drawVerticalLineStartPoint:(CGPoint) startPoint withEndPoint:(CGPoint) endPoint withColor:(UIColor *)color
{
    CAShapeLayer *layer=[CAShapeLayer layer];
    layer.lineCap=kCALineCapRound;
    layer.lineJoin=kCALineJoinBevel;
    layer.lineWidth=0.5;
    layer.fillColor=[UIColor clearColor].CGColor;
    [self.layer addSublayer:layer];

    UIBezierPath *bottomLinePath=[UIBezierPath bezierPath];
    [bottomLinePath moveToPoint:startPoint];
    [bottomLinePath addLineToPoint:endPoint];
    layer.path=bottomLinePath.CGPath;
    layer.strokeColor=[UIColor colorWithRed:0.902f green:0.902f blue:0.902f alpha:1.00f].CGColor;
}

//画点
-(void)drawPointWithCenterPoint:(CGPoint)point radius:(float)radius strokeColor:(UIColor *)strokeColor fillColor:(UIColor *)fillColor
{
    UIBezierPath *drawPoint=[UIBezierPath bezierPath];
    [drawPoint addArcWithCenter:point radius:radius startAngle:M_PI*0 endAngle:M_PI*2 clockwise:YES];
    CAShapeLayer *layer=[[CAShapeLayer alloc]init];
    layer.path=drawPoint.CGPath;
    layer.strokeColor=strokeColor.CGColor;
    layer.fillColor=fillColor.CGColor;
    [self.layer addSublayer:layer];
}

// 画文字 原本使用[NSstring drawAtPoint: withAttributes:]方法 但是画之后并不随着ScrollView滚动 所以用Label
-(void)drawText:(NSString *)text withPoint:(CGPoint)point withType:(TitleType) type withIndex:(NSInteger)index
{

    CGRect frame=[text boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:13.f]} context:nil];

    UILabel *label=[[UILabel alloc]init];

    CGPoint pointForValueString=CGPointMake(point.x-15, point.y);
    if (pointForValueString.y+frame.size.height>self.frame.size.height-50) {
        pointForValueString.y=point.y-frame.size.height-20;
    }
    else if (pointForValueString.y-frame.size.height<0)
    {
        pointForValueString.y=point.y+frame.size.height-20;
    }
    label.frame=CGRectMake(pointForValueString.x, pointForValueString.y, 30, 30);
    label.textAlignment=NSTextAlignmentCenter;
    if (type==TitleForPoint) {
        label.textColor=[UIColor redColor];
        label.font=[UIFont systemFontOfSize:13.f];
    }
    else if (type==TitleForX)
    {
        label.frame=CGRectMake(pointForValueString.x, pointForValueString.y+15, 30,30);
        if (_dataSource&&[_dataSource respondsToSelector:@selector(chart:backGroundColorAtXPointIndex:)]) {
            if ([_dataSource chart:self backGroundColorAtXPointIndex:index]) {
                label.backgroundColor=[UIColor redColor];
                label.textColor=[UIColor whiteColor];
                label.layer.cornerRadius=label.bounds.size.width/2;
                label.clipsToBounds=YES;
            }
            else
            {
                label.backgroundColor=[UIColor whiteColor];
                label.textColor=[UIColor colorWithRed:0.298f green:0.298f blue:0.298f alpha:1.00f];

            }

        }
        else
        {
            label.textColor=[UIColor colorWithRed:0.298f green:0.298f blue:0.298f alpha:1.00f];
        }
        label.font=[UIFont systemFontOfSize:14.f];
    }
    label.text=text;
    [self addSubview:label];
}

-(void)drawBrokenLine
{
     UIBezierPath *path=[UIBezierPath bezierPath];
    for (int i=0; i<self.count; i++) {
        CGFloat value=[_dataSource chart:self valueAtIndex:i];
        CGPoint point=[self pointWithValue:value index:i];

        //画竖线
        [self drawVerticalLineStartPoint:CGPointMake((i+0.5)*SPACING, self.frame.size.height-40) withEndPoint:point withColor:
         [UIColor blueColor]];

        //画折点
        [self drawPointWithCenterPoint:point radius:5 strokeColor:[UIColor redColor] fillColor:self.backgroundColor];

        //画X轴刻度点
        UIColor *pointColor=[UIColor colorWithRed:0.902f green:0.902f blue:0.902f alpha:1.00f];
        [self drawPointWithCenterPoint:CGPointMake((i+0.5)*SPACING, self.bounds.size.height-40) radius:3 strokeColor:pointColor fillColor:pointColor];

        //画文字
        NSString *valueString=[NSString stringWithFormat:@"%ld",(long)value];
        [self drawText:valueString withPoint:point withType:TitleForPoint withIndex:i];
        //画X轴
        if (_dataSource&&[_dataSource respondsToSelector:@selector(chart:titleForXLabelAtIndex:)]) {
            NSString *xstring=[_dataSource chart:self titleForXLabelAtIndex:i];
            [self drawText:xstring withPoint:CGPointMake(point.x, self.bounds.size.height-10) withType:TitleForX withIndex:i];
        }

        //画折线
        //贝塞尔曲线
        if (i==0) {
            [path moveToPoint:point];
        }else{
            [path addLineToPoint:point];
        }
    }

    path.lineCapStyle = kCGLineCapRound;
    path.lineJoinStyle=kCGLineJoinRound;
    path.lineWidth=0.5;
    [[UIColor redColor]setStroke];
    CABasicAnimation *pathAnimation=[CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = 2;
    pathAnimation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    pathAnimation.fromValue=[NSNumber numberWithFloat:0.0f];
    pathAnimation.toValue=[NSNumber numberWithFloat:1.0f];
    pathAnimation.autoreverses=NO;
    _linePath.path=path.CGPath;
    _linePath.strokeColor=[UIColor redColor].CGColor;
    [_linePath addAnimation:pathAnimation forKey:@"strokeEndAnimation"];
    _linePath.strokeEnd = 1.0;
}

//根据索引计算出折点的位置
-(CGPoint)pointWithValue:(NSInteger)value index:(NSInteger)index
{
    CGFloat height=self.frame.size.height;
    return  CGPointMake((index+0.5)*SPACING, height-value*self.avgHeight-40);
}
@end

调用:

#import "ViewController.h"
#import "LineChartView.h"

@interface ViewController ()<LineChartDataSource>
@property (nonatomic,strong) NSArray *points;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _points=@[@30,@40,@80,@10,@0,@70,@40,@80,@90,@20];

    LineChartView *lineChart=[[LineChartView alloc]initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width, 300)];

    lineChart.dataSource=self;

    [self.view addSubview:lineChart];
}

-(NSInteger)numberForChart:(LineChartView *)chart
{
    return _points.count;
}
-(float)chart:(LineChartView *)chart valueAtIndex:(NSInteger)index
{

    return [[_points objectAtIndex:index] floatValue];
}
-(NSString *)chart:(LineChartView *)chart titleForXLabelAtIndex:(NSInteger)index
{
    return [NSString stringWithFormat:@"10%ld",index];
}
-(BOOL)chart:(LineChartView *)chart backGroundColorAtXPointIndex:(NSInteger)index
{
    if (index==0) {
        return true;
    }
    else
    {
        return false;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

效果:

时间: 2023-01-10

IOS折线图的相关文章

IOS折线图二

上周把项目的折线图给做了下,今天想着把它完善完善,自己设置了不同的数据源来测试,哈哈,还真遇到问题了, 就是给图表设置折点数为0时,视图显示的还是原来的,由于数据为空,应该将其设置为空,所以想着怎么把ScrollView中的子视图情况.由于标题和折点值是用Label,可以删除View.但画的线和点是通过贝塞尔曲线添加到图层上了,还要把子视图的layer删掉.可是问题来了, 先上删除代码: int count = [self.layer.sublayers count]; for (int i =

swift:打造你自己的折线图

看到苹果Health里的折线图了吗.我们就是要打造一个这样的折线图.没看过的请看下图. 我们的主题在于折线图本身.其他的包括步数.日平均值等描述类的内容这里就不涉及了.   首先观察,这个图种包含些什么组成部分.线?这个太明显都看见了.还有每个节点的小圆圈,还有折线图里从上到下的渐变.这里是白色的从上到下逐渐透明的效果.还有一条虚线.这个暂时先不考虑了.你能绘制出来最下面的x轴标尺,绘制个虚线还不是小菜? 为什么说是绘制呢,因为显然我们不想用一个UIView把像素设置为1,背景色设置为UICol

ASP.NET画柱状图和折线图

asp.net|折线图|柱状图 using System;using System.Collections;using System.ComponentModel;using System.Data;using System.Drawing;using System.Web;using System.Web.SessionState;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.HtmlContro

raphael-Raphael做折线图时怎么设置图例?

问题描述 Raphael做折线图时怎么设置图例? Raphael做折线图时怎么设置图例?,网上的资料不是很多,麻烦请举例,研究了一下没研究出来

ASP生成柱型体、折线图、饼图源代码

饼图|源代码|折线图 终于将这三个写成函数,可以方便大家调用,示例如下,如果有不妥之处,希望和大家多交流.如果你喜欢这个程序的话,请回复一下,是对我的支持,也希望和大家交朋友,多切磋.也请斑竹多支持! 因本站为PHP空间所以不提供演示地址 代码:<%function table2(total,table_x,table_y,all_width,all_height,line_no)'参数含义(传递的数组,横坐标,纵坐标,图表的宽度,图表的高度,折线条数)'纯ASP代码生成图表函数2--折线图li

ASP生成柱型体,折线图,饼图源代码

饼图|源代码|折线图    <%   function table2(total,table_x,table_y,all_width,all_height,line_no)   '参数含义(传递的数组,横坐标,纵坐标,图表的宽度,图表的高度,折线条数)   '纯ASP代码生成图表函数2--折线图   '作者:龚鸣(Passwordgm) QQ:25968152 MSN:passwordgm@sina.com Email:passwordgm@sina.com   '本人非常愿意和ASP,VML,

纯ASP结合VML生成完美图-折线图

折线图 演示地址:http://61.172.255.65/dvbbs/t3/t18.asp <%dim total(7,3)total(1,0)="中国经营报"total(2,0)="招聘网"total(3,0)="51Job"total(4,0)="新民晚报"total(5,0)="新闻晚报"total(6,0)="南方周末"total(7,0)="羊城晚报"

用代码画折线图/柱形图/条形图/饼图

饼图|折线图|柱形图 本文将介绍在.Net中如何使用代码画图表,就像用MS Excel生成的图表一样.也可以画像DataGrid一样的表格. 在.Net中,微软给我们提供了画图类(System.Drawing.Imaging),在该类中画图的基本功能都有.比如:直线.折线.矩形.多边形.椭圆形.扇形.曲线等等,因此一般的图形都可以直接通过代码画出来.接下来介绍一些画图函数:Bitmap bMap=new Bitmap(500,500) //定义图像大小:bMap.Save(Stream,Imag

用GD图库生成横竖柱状图折线图的类

折线图|柱状图 最近写的一个GD图库用以生成横竖柱状图和折线图的类库,算是一个教学例程吧  <? Class ImageReport{ var $X;//图片大小X轴 var $Y;//图片大小Y轴 var $R;//背影色R值 var $G;//...G. var $B;//...B. var $TRANSPARENT;//是否透明1或0 var $IMAGE;//图片对像 //------------------- var $ARRAYSPLIT;//指定用于分隔数值的符号 var $ITE