MPAndroidChart开源图表库之饼状图

今天做的项目一个需求是做一个饼图的统计图,于是查找资料,最后发现MPAndroidChart是一款基于Android的开源图表库,MPAndroidChart不仅可以在Android设备上绘制各种统计图表,而且可以对图表进行拖动和缩放操作,应用起来非常灵活。于是就用了它实现了想要的效果。MPAndroidChart同样拥有常用的图表类型:线型图、饼图、柱状图和散点图。

GitHub地址:

https://github.com/PhilJay/MPAndroidChart

现看一下效果图

                                   MPAndroidChart开源图表库之饼状图_第1张图片                                     

下面通过AndroidStudio实现饼状图:

1、先在build.gradle里添加如下内容

repositories {
    maven { url "https://jitpack.io" }
}

dependencies {
    compile 'com.github.PhilJay:MPAndroidChart:v2.2.5'
}
2、在.xml里设置布局

<com.github.mikephil.charting.charts.PieChart
    android:id="@+id/pieChart"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1">
com.github.mikephil.charting.charts.PieChart>
3、PieChart类的内容如下

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.view.Gravity;
import android.widget.GridLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.qise.piechart.piechart.R;

import java.util.ArrayList;

public class PieChartActivity extends Activity {

    private PieChart pieChart;
    private GridLayout legendLayout;
    private int[] colors = {R.color.PIE_PINK,R.color.PIE_ORANGE,R.color.PIE_YELLOW,R.color.PIE_GREEN,R.color.PIE_BLUE};//颜色集合
    private String[] datas={"人脉关系","身份特质","履约能力","行为爱好","信用历史"};//数据,可以是任何类型的数据,如String,int

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pie_chart);
        pieChart = (PieChart) findViewById(R.id.pieChart);
        legendLayout = (GridLayout) findViewById(R.id.legendLayout);
        initChart();
    }

    private void initChart() {
        // 设置饼图是否接收点击事件,默认为true
        pieChart.setTouchEnabled(true);
        //设置饼图是否使用百分比
        pieChart.setUsePercentValues(true);
        //设置饼图右下角的文字描述
        pieChart.setDescription("");
        //设置饼图右下角的文字描述   文字位置
        pieChart.setDescriptionPosition(460,730);
        //设置饼图右下角的文字大小
        pieChart.setDescriptionTextSize(16);
        pieChart.setExtraOffsets(15, -20, 15, 0);//left   top  right  bottom

        //是否显示圆盘中间文字,默认显示
        pieChart.setDrawCenterText(true);
        pieChart.setHoleColor(Color.WHITE);//设置中间圆盘的颜色
        //设置圆盘中间文字
        pieChart.setCenterText(generateCenterSpannableText());
        pieChart.setTransparentCircleColor(getResources().getColor(R.color.bantouming));
//        pieChart.setTransparentCircleAlpha(100);

        pieChart.setHoleRadius(60); //设置中间圆盘的半径,值为所占饼图的百分比
        pieChart.setTransparentCircleRadius(63); //设置中间透明圈的半径,值为所占饼图的百分比

        pieChart.setDrawCenterText(true);//饼状图中间可以添加文字

        //设置圆盘是否转动,默认转动
        pieChart.setRotationEnabled(true);
        //设置初始旋转角度
        pieChart.setRotationAngle(100);

//        //设置比例图
//        Legend mLegend = pieChart.getLegend();
//        //设置比例图显示在饼图的哪个位置
//        mLegend.setPosition(Legend.LegendPosition.BELOW_CHART_LEFT);
//        //设置比例图的形状,默认是方形,可为方形、圆形、线性
//        mLegend.setForm(Legend.LegendForm.SQUARE);
//        mLegend.setXEntrySpace(0f);//设置距离饼图的距离,防止与饼图重合
//        mLegend.setYEntrySpace(0f);
//        mLegend.setYOffset(0f);
//        //设置比例块换行...
//        mLegend.setWordWrapEnabled(true);

        customizeLegend();

        //设置X轴动画
//        pieChart.animateX(1800);
//        //设置y轴动画
//        pieChart.animateY(1800);
//        //设置xy轴一起的动画
//        pieChart.animateXY(1800, 1800);

        //绑定数据
        bindData(5);

        // 设置一个选中区域监听
        pieChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
                pieChart.setDescription(datas[e.getXIndex()] + " " + (int)e.getVal() + "");
            }
            @Override
            public void onNothingSelected() {
            }
        });
    }

    /**
     *
     * @param count 分成几部分
     */
    private void bindData(int count) {
        /**
         * nameList用来表示每个饼块上的文字内容
         * 如:部分一,部分二,部分三
         */
        ArrayList nameList = new ArrayList();
        for (int i = 0; i < count; i++) {
//            nameList.add("部分" + (i + 1));
            nameList.add("");
        }
        /**
         * valueList将一个饼形图分成三部分,各个区域的百分比的值
         * Entry构造函数中
         * 第一个值代表所占比例,
         * 第二个值代表区域位置
         * (可以有第三个参数,表示携带的数据object)这里没用到
         */
        ArrayList valueList = new ArrayList();
        valueList.add(new Entry(60, 0));
        valueList.add(new Entry(20, 1));
        valueList.add(new Entry(10, 2));
        valueList.add(new Entry(4, 3));
        valueList.add(new Entry(6, 4));

        //显示在比例图上
        PieDataSet dataSet = new PieDataSet(valueList, "");
        //设置各个饼状图之间的距离
        dataSet.setSliceSpace(0f);
        // 部分区域被选中时多出的长度
        dataSet.setSelectionShift(15f);

        // 设置饼图各个区域颜色
        ArrayList colors = new ArrayList();
        colors.add(getResources().getColor(R.color.PIE_BLUE));
        colors.add(getResources().getColor(R.color.PIE_GREEN));
        colors.add(getResources().getColor(R.color.PIE_YELLOW));
        colors.add(getResources().getColor(R.color.PIE_ORANGE));
        colors.add(getResources().getColor(R.color.PIE_PINK));
        dataSet.setColors(colors);

        PieData data = new PieData(nameList, dataSet);
        //设置以百分比显示
        data.setValueFormatter(new PercentFormatter());
        //区域文字的大小
        data.setValueTextSize(11f);
        //设置区域文字的颜色
        data.setValueTextColor(Color.WHITE);
        //设置区域文字的字体
        data.setValueTypeface(Typeface.DEFAULT);

        pieChart.setData(data);

        //设置是否显示区域文字内容
        pieChart.setDrawSliceText(pieChart.isDrawSliceTextEnabled());
        //设置是否显示区域百分比的值
        for (IDataSet set : pieChart.getData().getDataSets()){
            set.setDrawValues(!set.isDrawValuesEnabled());
        }
        // undo all highlights
        pieChart.highlightValues(null);
        pieChart.invalidate();
    }

    //中间显示的文字数据
    private SpannableString generateCenterSpannableText() {
        SpannableString s = new SpannableString("信用分数\n769");
        s.setSpan(new RelativeSizeSpan(1.2f), 0, 4, 0);
        s.setSpan(new StyleSpan(Typeface.NORMAL), 0, 4, 0);
        s.setSpan(new ForegroundColorSpan(Color.BLACK), 0, 4, 0);
        s.setSpan(new RelativeSizeSpan(3.8f), 4, s.length(), 0);
        s.setSpan(new StyleSpan(Typeface.BOLD), 4, s.length(), 0);
        s.setSpan(new ForegroundColorSpan(Color.RED), 4, s.length(), 0);
        return s;
    }

    /**
     * 定制图例,通过代码生成布局
     */
    private void customizeLegend(){
        Legend legend=pieChart.getLegend();//设置比例图
        legend.setEnabled(false);//图例不显示

        for(int i=0;i<datas.length;i++){
            LinearLayout.LayoutParams lp=new LinearLayout.
                    LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.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(30, 10, 10, 10);//int left, int top, int right, int bottom
            LinearLayout colorLayout=new LinearLayout(this);
            colorLayout.setLayoutParams(colorLP);
            colorLayout.setBackgroundColor(getResources().getColor(colors[i]));
            layout.addView(colorLayout);

            //添加data
            TextView dataTV=new TextView(this);
            dataTV.setText(datas[i]+"");
            dataTV.setTextSize(12f);
            layout.addView(dataTV);
            legendLayout.addView(layout);//legendLayout为外层布局即整个图例布局,是在xml文件中定义
        }
    }
}
上面的代码注释已经很详细了,相信您可以看懂的,如果您感觉哪里有不足的地方请提出来,我们一起研究进步。

源码下载地址:http://download.csdn.net/detail/u013184970/9592817


MPAndroidChart源码地址:http://download.csdn.net/detail/u013184970/9592794


MPAndroidChart可以绘制各种常用的图表类型:折线图、柱形图、饼图、散点图等等


github地址:https://github.com/PhilJay/MPAndroidChart


你可能感兴趣的:(Android,知识点小模块例子)