iOS使用Charts框架绘制饼状图

2020-01-18 19:29:04丽君

首先先看一下效果:

iOS,Charts,饼状图

饼状图

一、创建饼状图对象

创建饼状图对象用到类是PieChartView.h,


self.pieChartView = [[PieChartView alloc] init];
self.pieChartView.backgroundColor = BgColor;
[self.view addSubview:self.pieChartView];
[self.pieChartView mas_makeConstraints:^(MASConstraintMaker *make) {
  make.size.mas_equalTo(CGSizeMake(300, 300));
  make.center.mas_equalTo(self.view);
}];

二、设置饼状图外观样式

1. 基本样式


[self.pieChartView setExtraOffsetsWithLeft:30 top:0 right:30 bottom:0];//饼状图距离边缘的间隙
self.pieChartView.usePercentValuesEnabled = YES;//是否根据所提供的数据, 将显示数据转换为百分比格式
self.pieChartView.dragDecelerationEnabled = YES;//拖拽饼状图后是否有惯性效果
self.pieChartView.drawSliceTextEnabled = YES;//是否显示区块文本

2. 设置饼状图中间的空心样式

空心有两个圆组成, 一个是hole, 一个是transparentCircle, transparentCircle里面是hole, 所以饼状图中间的空心也就是一个同心圆.


self.pieChartView.drawHoleEnabled = YES;//饼状图是否是空心
self.pieChartView.holeRadiusPercent = 0.5;//空心半径占比
self.pieChartView.holeColor = [UIColor clearColor];//空心颜色
self.pieChartView.transparentCircleRadiusPercent = 0.52;//半透明空心半径占比
self.pieChartView.transparentCircleColor = [UIColor colorWithRed:210/255.0 green:145/255.0 blue:165/255.0 alpha:0.3];//半透明空心的颜色

3. 设置饼状图中心的文本

当饼状图是空心样式时, 可以在饼状图中心添加文本, 添加文本有两种方法. 一种方法是使用centerText 属性添加, 这种方法不能设置字体颜色、大小等. 另一种方法是使用centerAttributedText属性添加, 这种方法添加的富文本, 因此就可以对字体进行进一步美化了.


if (self.pieChartView.isDrawHoleEnabled == YES) {
  self.pieChartView.drawCenterTextEnabled = YES;//是否显示中间文字
  //普通文本
//  self.pieChartView.centerText = @"饼状图";//中间文字
  //富文本
  NSMutableAttributedString *centerText = [[NSMutableAttributedString alloc] initWithString:@"饼状图"];
  [centerText setAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:16],
         NSForegroundColorAttributeName: [UIColor orangeColor]}
       range:NSMakeRange(0, centerText.length)];
  self.pieChartView.centerAttributedText = centerText;
}

4. 设置饼状图描述


self.pieChartView.descriptionText = @"饼状图示例";
self.pieChartView.descriptionFont = [UIFont systemFontOfSize:10];
self.pieChartView.descriptionTextColor = [UIColor grayColor];