美文网首页Swift 客户端开发
iOS 使用charts绘制饼图、折线图、K线图(混合图表)

iOS 使用charts绘制饼图、折线图、K线图(混合图表)

作者: OrrHsiao | 来源:发表于2018-10-30 11:20 被阅读0次

    charts是iOS上一个非常优秀的使用swift编写的图表框架,点击查看项目github链接,使用该框架可以轻松的绘制出非常漂亮的图表,但是由于是swift写的,导致在OC编写的项目中集成起来比较困难,如何集成可以看一下我之前写的一篇文章

    图片来源于github该项目 图片来源于github该项目 图片来源于github该项目 图片来源于github该项目 图片来源于github该项目 图片来源于github该项目 图片来源于github该项目 图片来源于github该项目 图片来源于github该项目 图片来源于github该项目 图片来源于github该项目 图片来源于github该项目 图片来源于github该项目

    以下是我实现的部分图表的代码,仅供参考

    饼图
    - (PieChartView *)chartView
    {
        if (!_chartView) {
            _chartView = [[PieChartView alloc] init];
            _chartView.backgroundColor = [UIColor clearColor];
            //设置没有数据时显示的内容
            _chartView.noDataText = @"未获取到数据";
            //饼状图距离边缘的间隙
            [_chartView setExtraOffsetsWithLeft:0 top:12 right:0 bottom:5];
            //显示空心
            _chartView.drawHoleEnabled = YES;
            //透明圈的占比
            _chartView.transparentCircleRadiusPercent = 0;
            //空心的颜色
            _chartView.holeColor = [UIColor colorWithRed:20/255.0 green:43/255.0 blue:59/255.0 alpha:1/1.0];
            //中间空心的占比
            _chartView.holeRadiusPercent = 0.55;
            //不允许旋转
            _chartView.rotationEnabled = NO;
            //设置图例在视图中占的比例
            _chartView.legend.maxSizePercent = 1.2;//图例在饼状图中的大小占比, 这会影响图例的宽高
            _chartView.legend.formToTextSpace = 5;//文本间隔
            _chartView.legend.font = [UIFont systemFontOfSize:10];//字体大小
            _chartView.legend.textColor = [UIColor clearColor];//字体颜色
            _chartView.legend.form = ChartLegendFormCircle;//图示样式: 方形、线条、圆形
            //设置图示大小为0
            _chartView.legend.formSize = 0;//图示大小
            //居中
            _chartView.legend.horizontalAlignment = ChartLegendHorizontalAlignmentCenter;
            //下方
            _chartView.legend.verticalAlignment = ChartLegendVerticalAlignmentBottom;
            //横着显示
            _chartView.legend.orientation = ChartLegendOrientationHorizontal;
            //设置description
            ChartDescription *des = [[ChartDescription alloc] init];
            des.text = @"";
            des.font = [UIFont systemFontOfSize:10*SCALE];
            des.textAlign = NSTextAlignmentLeft;
            des.textColor = [UIColor whiteColor];
            [_chartView setChartDescription:des];
        }
        return _chartView;
    }
    
    - (void)setDataWithModel:(NSArray *)arr
    {
        //饼状图总共有几块组成
        NSInteger count = arr.count;
        //每个区块内的数据
        NSMutableArray *yVals = [[NSMutableArray alloc] init];
        for (int i = 0; i < count; i++) {
            CoinRatioModel *model = arr[i];
            double value = [[model.ratio substringToIndex:model.ratio.length - 1] doubleValue];
            NSString *name = model.coinName;
            PieChartDataEntry *entry = [[PieChartDataEntry alloc] initWithValue:value label:name];
            [yVals addObject:entry];
        }
        
        PieChartDataSet *dataSet = [[PieChartDataSet alloc] initWithValues:yVals label:@""];
        dataSet.drawValuesEnabled = YES;
        NSMutableArray *colors = [NSMutableArray arrayWithCapacity:0];
        [colors addObject:[UIColor colorWithRed:114/255.0 green:179/255.0 blue:249/255.0 alpha:1/1.0]];
        [colors addObject:[UIColor colorWithRed:85/255.0 green:157/255.0 blue:233/255.0 alpha:1/1.0]];
        [colors addObject:[UIColor colorWithRed:74/255.0 green:148/255.0 blue:227/255.0 alpha:1/1.0]];
        [colors addObject:[UIColor colorWithRed:54/255.0 green:121/255.0 blue:193/255.0 alpha:1/1.0]];
        [colors addObject:[UIColor colorWithRed:38/255.0 green:100/255.0 blue:167/255.0 alpha:1/1.0]];
        [colors addObject:[UIColor colorWithRed:29/255.0 green:83/255.0 blue:142/255.0 alpha:1/1.0]];
        [colors addObject:[UIColor colorWithRed:26/255.0 green:69/255.0 blue:110/255.0 alpha:1/1.0]];
        dataSet.colors = colors;
        //相邻区块间距
        dataSet.sliceSpace = 0;
        //选中区块时, 放大的半径
        dataSet.selectionShift = 0;
        dataSet.xValuePosition = PieChartValuePositionOutsideSlice;//名称位置
        dataSet.yValuePosition = PieChartValuePositionOutsideSlice;//数据位置
        //数据与区块之间的用于指示的折线样式
        dataSet.valueLinePart1OffsetPercentage = 0.85;//折线中第一段起始位置相对于区块的偏移量, 数值越大, 折线距离区块越远
        dataSet.valueLinePart1Length = 0.4;//折线中第一段长度占比
        dataSet.valueLinePart2Length = 2;//折线中第二段长度最大占比
        dataSet.valueLineWidth = 1;//折线的粗细
        dataSet.valueLineColor = [UIColor colorWithRed:152/255.0 green:199/255.0 blue:248/255.0 alpha:1];//折线颜色
        dataSet.valueFont = [UIFont systemFontOfSize:10*SCALE];
        dataSet.valueColors = @[[UIColor whiteColor],[UIColor whiteColor],[UIColor whiteColor]];
        
        PieChartData *data = [[PieChartData alloc] initWithDataSet:dataSet];
        NSNumberFormatter *pFormatter = [[NSNumberFormatter alloc] init];
        pFormatter.numberStyle = NSNumberFormatterPercentStyle;
        pFormatter.maximumFractionDigits = 4;
        pFormatter.multiplier = @1.f;
        pFormatter.percentSymbol = @" %";
        [data setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:pFormatter]];
        [data setValueTextColor:[UIColor whiteColor]];
        [data setValueFont:[UIFont systemFontOfSize:10*SCALE]];
        
        [self.chartView setData:data];
    }
    
    折线图
    - (LineChartView *)lineChartView
    {
        if (!_lineChartView) {
            _lineChartView = [[LineChartView alloc] init];
            //禁止X轴拖拽
            _lineChartView.scaleXEnabled = NO;
            //禁止Y轴拖拽
            _lineChartView.scaleYEnabled = NO;
            //不显示描述
            _lineChartView.chartDescription.enabled = NO;
            //不显示图例
            _lineChartView.legend.enabled = NO;
            //不显示左边坐标轴
            _lineChartView.leftAxis.enabled = NO;
            //不显示右边坐标轴
            _lineChartView.rightAxis.enabled = NO;
            //不显示X轴
            _lineChartView.xAxis.enabled = NO;
        }
        return _lineChartView;
    }
    
    //设置数据源方法
    - (void)setDataArr:(NSArray<NSString *> *)dataArr
    {
        _dataArr = dataArr;
        //定义一个数组承接数据
        //对应Y轴上面需要显示的数据
        NSMutableArray *yVals = [[NSMutableArray alloc] init];
        for (int i = 0; i < dataArr.count; i++) {
            //将横纵坐标以ChartDataEntry的形式保存下来,注意横坐标值一般是i的值,而不是你的数据
            //里面具体的值,如何将具体数据展示在X轴上我们下面将会说到。
            double yValue = [dataArr[i] doubleValue];
            ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:i y:yValue];
            [yVals addObject:entry];
        }
        LineChartDataSet *set1 = nil;
        //请注意这里,如果你的图表以前绘制过,那么这里直接重新给data赋值就行了。
        //如果没有,那么要先定义set的属性。
        if (self.lineChartView.data.dataSetCount > 0) {
            LineChartData *data = (LineChartData *)self.lineChartView.data;
            set1 = (LineChartDataSet *)data.dataSets[0];
            set1 = (LineChartDataSet *)self.lineChartView.data.dataSets[0];
            set1.values = yVals;
            //通知data去更新
            [self.lineChartView.data notifyDataChanged];
            //通知图表去更新
            [self.lineChartView notifyDataSetChanged];
        }else
        {
            //创建LineChartDataSet对象
            set1 = [[LineChartDataSet alloc] initWithValues:yVals];
            //自定义set的各种属性
            //设置为绘制贝塞尔曲线
    //        set1.mode = LineChartModeCubicBezier;
            //设置折线的样式
            set1.drawIconsEnabled = NO;
            //折线宽度
            set1.formLineWidth = 1.1;
            set1.formSize = 15.0;
            //是否在拐点处显示数据
            set1.drawValuesEnabled = NO;
            //折线拐点处显示数据的颜色
            set1.valueColors = @[[UIColor redColor]];
            //折线颜色
            [set1 setColor:[UIColor colorWithRed:227/255.0 green:72/255.0 blue:74/255.0 alpha:1]];
            //是否绘制拐点
            set1.drawCirclesEnabled = NO;
            //渐变填充
            set1.drawFilledEnabled = YES;
            NSArray *gradientColors = @[(id)[UIColor colorWithRed:251/255.0 green:188/255.0 blue:189/255.0 alpha:0.1].CGColor,(id)[UIColor colorWithRed:227/255.0 green:72/255.0 blue:74/255.0 alpha:1].CGColor];
            CGGradientRef gradientRef = CGGradientCreateWithColors(nil, (CFArrayRef)gradientColors, nil);
            //透明度
            set1.fillAlpha = 1.0f;
            set1.fill = [ChartFill fillWithLinearGradient:gradientRef angle:90.0f];//赋值填充颜色对象
            //释放gradientRef
            CGGradientRelease(gradientRef);
            //点击选中拐点的交互样式
            //选中拐点,是否开启高亮效果(显示十字线)
            set1.highlightEnabled = NO;
            //将 LineChartDataSet 对象放入数组中
            NSMutableArray *dataSets = [[NSMutableArray alloc] init];
            [dataSets addObject:set1];
            //创建 LineChartData 对象, 此对象就是lineChartView需要最终数据对象
            LineChartData *data = [[LineChartData alloc] initWithDataSets:dataSets];
            //文字字体
            [data setValueFont:[UIFont systemFontOfSize:8.f]];
            //文字颜色
            [data setValueTextColor:[UIColor redColor]];
            
            self.lineChartView.data = data;
        }
    }
    
    混合图表
    - (CombinedChartView *)chartView
    {
        if (!_chartView) {
            _chartView = [[CombinedChartView alloc] init];
            _chartView.backgroundColor = [UIColor colorWithRed:20/255.0 green:43/255.0 blue:59/255.0 alpha:1/1.0];
            _chartView.leftAxis.enabled = NO;
            _chartView.rightAxis.labelTextColor = [UIColor grayColor];
            _chartView.xAxis.drawLabelsEnabled = NO;
            //X轴数据显示在下面
            _chartView.xAxis.labelPosition = XAxisLabelPositionBottom;
            //右Y轴数据显示在内部
            _chartView.rightAxis.labelPosition = YAxisLabelPositionInsideChart;
            //禁止X轴拖拽
            _chartView.scaleXEnabled = NO;
            //禁止Y轴拖拽
            _chartView.scaleYEnabled = NO;
            //不显示描述
            _chartView.chartDescription.enabled = NO;
            //不显示图例
            _chartView.legend.enabled = NO;
            //设置绘制顺序
            _chartView.drawOrder = @[@(CombinedChartDrawOrderCandle),@(CombinedChartDrawOrderLine)];
            //设置右Y轴坐标显示个数
            _chartView.rightAxis.labelCount = 4;
        }
        return _chartView;
    }
    
    /**
     获取一条折线数据
    
     @param dataArr <#dataArr description#>
     @return <#return value description#>
     */
    - (LineChartDataSet *)getLineWithArr:(NSArray *)dataArr lineColor:(UIColor *)lineColor
    {
        //对应Y轴上面需要显示的数据
        NSMutableArray *yVals = [[NSMutableArray alloc] init];
        for (int i = 0; i < dataArr.count; i++) {
            //将横纵坐标以ChartDataEntry的形式保存下来,注意横坐标值一般是i的值,而不是你的数据
            //里面具体的值,如何将具体数据展示在X轴上我们下面将会说到。
            double yValue = [dataArr[i] doubleValue];
            ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:i y:yValue];
            [yVals addObject:entry];
        }
        //创建LineChartDataSet对象
        LineChartDataSet *set = [[LineChartDataSet alloc] initWithValues:yVals];
        //自定义set的各种属性
        //设置折线的样式
        set.drawIconsEnabled = NO;
        //折线宽度
        set.formLineWidth = 1.1;
        set.formSize = 15.0;
        //是否在拐点处显示数据
        set.drawValuesEnabled = NO;
        //折线颜色
        [set setColor:lineColor];
        //是否绘制拐点
        set.drawCirclesEnabled = NO;
        //渐变填充
        set.drawFilledEnabled = NO;
        //点击选中拐点的交互样式
        //选中拐点,是否开启高亮效果(显示十字线)
        set.highlightEnabled = NO;
        //设置为绘制贝塞尔曲线
        set.mode = LineChartModeCubicBezier;
        return set;
    }
    
    /**
     生成一组随机数
    
     @param count 个数
     @param max 最大值
     @return 一组随机数
     */
    - (NSArray *)getRandomArrWithCount:(NSInteger)count max:(int)max
    {
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
        for (int i = 0; i < count; i++) {
            CGFloat val = (arc4random_uniform(max));
            NSString *str = [NSString stringWithFormat:@"%f",val];
            [arr addObject:str];
        }
        return arr;
    }
    
    /**
     获取折线数据
     */
    - (LineChartData *)getLineData
    {
        //折线一
        LineChartDataSet *set1 = [self getLineWithArr:[self getRandomArrWithCount:40 max:50]  lineColor:[UIColor greenColor]];
        //折线二
        LineChartDataSet *set2 = [self getLineWithArr:[self getRandomArrWithCount:40 max:100]  lineColor:[UIColor yellowColor]];
        //创建 LineChartData 对象, 此对象就是lineChartView需要最终数据对象
        LineChartData *data = [[LineChartData alloc] initWithDataSets:@[set1,set2]];
        //文字字体
    //    [data setValueFont:[UIFont systemFontOfSize:8.f]];
        //文字颜色
    //    [data setValueTextColor:[UIColor redColor]];
        return data;
    }
    
    - (CandleChartData *)getCandleData
    {
        NSMutableArray *yVals = [[NSMutableArray alloc] init];
        // 产生40个随机立柱数据
        for (int i = 0; i < 40; i ++) {
            CGFloat val = (arc4random_uniform(80));
            CGFloat high = (arc4random_uniform(9)) + 8.0;
            CGFloat low = (arc4random_uniform(9)) + 8.0;
            CGFloat open = (arc4random_uniform(8)) + 2.0;
            CGFloat close = (arc4random_uniform(8)) + 2.0;
            
            CGFloat even = i % 2 == 0;
            
            CandleChartDataEntry *y = [[CandleChartDataEntry alloc] initWithX:i shadowH:val + high shadowL:val - low open:even  ? val + open : val - open close:even ? val + close : val - close];
            
            [yVals addObject:y];
        }
        
        CandleChartDataSet *set = [[CandleChartDataSet alloc] initWithValues:yVals];
        
        //这是用于显示最高最低值区间的立线
    //    set.shadowColor = [UIColor whiteColor];
        //设置用于显示最高最低值区间的立线颜色与内部颜色保持一致
        set.shadowColorSameAsCandle = YES;
        //不在面板上直接显示数值
        set.drawValuesEnabled = NO;
        // 立线的宽度
        set.shadowWidth = 1;
        // close >= open
        set.increasingColor = [UIColor colorWithRed:227/255.0 green:72/255.0 blue:74/255.0 alpha:1/1.0];
        // 内部是否充满颜色
        set.increasingFilled = YES;
        // open > close
        set.decreasingColor = [UIColor colorWithRed:32/255.0 green:179/255.0 blue:94/255.0 alpha:1];
        // 内部是否充满颜色
        set.decreasingFilled = YES;
        //自然状态下的颜色
        set.neutralColor = [UIColor whiteColor];
        
        CandleChartData *data = [[CandleChartData alloc] initWithDataSet:set];
        
        return data;
    }
    

    相关文章

      网友评论

        本文标题:iOS 使用charts绘制饼图、折线图、K线图(混合图表)

        本文链接:https://www.haomeiwen.com/subject/uonwtqtx.html