android MPAndroidChart饼图实现图例后加数字或文本(定制图例)

时间:2021-10-31 01:58:29

转载请注明:http://blog.csdn.net/ly20116/article/details/50905789

MPAndroidChart是一个非常优秀的开源图表库,MPAndroidChart可以绘制各种常用的图表类型:折线图、柱形图、饼图、散点图等等。 
github地址:https://github.com/PhilJay/MPAndroidChart 
具体的导入方式就不再详细的说了,本文主要解决在图例后面加上数字或文本或占的百分比等,也就是定制想要的图例。 
MPAndroidChart的提供的饼图图例是这种: (注:图片为引用) 
android MPAndroidChart饼图实现图例后加数字或文本(定制图例) android MPAndroidChart饼图实现图例后加数字或文本(定制图例)

而我们想要实现的效果是这种: 
android MPAndroidChart饼图实现图例后加数字或文本(定制图例)

就是在图例后面加上数字或文本

通过借鉴*上的大神的解决方案: 
https://*.com/questions/29139061/mpandroidchart-legend-customization

下面来开始我们的项目: 
一、获取Legend,使Legend不显示

Legend legend=mPieChart.getLegend();//设置比例图
legend.setEnabled(false);//图例不显示
  • 1
  • 2

二、定义数组colors和labels及数据datas

private int[] colors;//颜色集合
private String[] labels;//标签文本
private float[] datas={16912f,2488f,600f};//数据,可以是任何类型的数据,如String,int
  • 1
  • 2
  • 3

三、获取Legend中的colors和labels

colors=legend.getColors();
labels=legend.getLabels();
  • 1
  • 2

四、定义customizeLegend()方法,实现图例的绘制

/**
* 定制图例,通过代码生成布局
*/
private void customizeLegend(){
for(int i=0;i<datas.length;i++){
LinearLayout.LayoutParams lp=new LinearLayout.
LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
lp.weight=1;//设置比重为1
LinearLayout layout=new LinearLayout(this);//单个图例的布局
layout.setOrientation(LinearLayout.HORIZONTAL);//水平排列
layout.setGravity(Gravity.CENTER_VERTICAL);//垂直居中
layout.setLayoutParams(lp); //添加color
LinearLayout.LayoutParams colorLP=new LinearLayout.
LayoutParams(20,20);
colorLP.setMargins(0, 0, 20, 0);
LinearLayout colorLayout=new LinearLayout(this);
colorLayout.setLayoutParams(colorLP);
colorLayout.setBackgroundColor(colors[i]);
layout.addView(colorLayout); //添加label
TextView labelTV=new TextView(this);
labelTV.setText(labels[i]+" ");
layout.addView(labelTV); //添加data
TextView dataTV=new TextView(this);
dataTV.setText(datas[i]+"");
layout.addView(dataTV); legendLayout.addView(layout);//legendLayout为外层布局即整个图例布局,是在xml文件中定义 }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

图例示意图: 
android MPAndroidChart饼图实现图例后加数字或文本(定制图例)

customizeLegend()方法的调用可在设置图例不显示的后面,也可以在其它地方调用,但是必须在PieChart调用setData()方法的后面,这样才能获取到colors和labels.

总结: 
简而言之,就是获取legend的颜色colors和标签文本labels,然后结合自己的数据,在新的布局中绘制即可。 
你可以在图例后面添加更多的类型的数据。 
图例布局的位置可以在xml文件中设置。 
也可以实现各种布局的图例