结合项目经验来谈使用MPAndoridChart的总结(一)

MPAndroidChart是一款基于Android的开源图表库,MPAndroidChart不仅可以在Android设备上绘制各种统计图表,而且可以对图表进行拖动和缩放操作,应用起来非常灵活,并且功能强大,有Android图表“一哥”的称号。
其官方地址为:MPAndroidChart

使用时需要注意,不同版本的MPAndroidChart的API有所差异。
我们项目中使用的是3.0版本。

需要使用到MPAndroidChart,很简单,只需添加依赖即可。

implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'

下面我们结合项目需求来进行一些讲解:
画饼图。
在这里插入图片描述
效果如上。
我们使用PieChart这个类。
1、在布局文件中,

 <com.github.mikephil.charting.charts.PieChart
                        android:id="@+id/pieChart"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"/>

2、java代码,
我们可以根据我们最终想要的效果进行一系列的设置。
下面举例:
pieChart.getDescription().setEnabled(false); //不显示描述(描述是默认显示的)
或者
Description description = new Description();
description.setEnabled(false);
pieChart.setDescription(description); //同样是不显示描述

pieChart.getLegend().setEnabled(false); //禁用图标图例(默认是有图表图例的)
pieChart.setUsePercentValues(true); //如果启用此选项,则PieChart中的值将以百分比形式绘制,而不是以其原始值绘制。然后以百分比形式提供为IValueFormatter格式化提供的值。
pieChart.setHoleRadius(58f); //设置饼图中心的孔半径,以最大半径的百分比表示(max = 整个图表的半径),默认为50%
对应的源码中方法的定义如下:

    /**
     * sets the radius of the hole in the center of the piechart in percent of
     * the maximum radius (max = the radius of the whole chart), default 50%
     *
     * @param percent
     */
    public void setHoleRadius(final float percent) {
        mHoleRadiusPercent = percent;
    }

    /**
     * indicates the size of the hole in the center of the piechart, default:
     * radius / 2
     */
    private float mHoleRadiusPercent = 50f;

pieChart.setTransparentCircleRadius(61f);
//设置在饼图中孔旁边绘制的透明圆的半径,以最大半径的百分比表示(max = 整个图表的半径),默认为55%->表示默认比中心孔大5%
对应的源码中方法定义如下:

    /**
     * sets the radius of the transparent circle that is drawn next to the hole
     * in the piechart in percent of the maximum radius (max = the radius of the
     * whole chart), default 55% -> means 5% larger than the center-hole by
     * default
     *
     * @param percent
     */
    public void setTransparentCircleRadius(final float percent) {
        mTransparentCircleRadiusPercent = percent;
    }
    
    /**
     * the radius of the transparent circle next to the chart-hole in the center
     */
    protected float mTransparentCircleRadiusPercent = 55f;

pieChart.setDrawCenterText(true); //设置饼图中间可以添加文字,默认为可以在饼图中间添加文字
对应的源码如下:

    /**
     * set this to true to draw the text that is displayed in the center of the
     * pie chart
     *
     * @param enabled
     */
    public void setDrawCenterText(boolean enabled) {
        this.mDrawCenterText = enabled;
    }
    
    /**
     * if enabled, centertext is drawn
     */
    private boolean mDrawCenterText = true;

pieChart.setDrawHoleEnabled(true); //设置饼图中间画孔,默认为饼图中间画孔
对应的源码如下:

    /**
     * set this to true to draw the pie center empty
     *
     * @param enabled
     */
    public void setDrawHoleEnabled(boolean enabled) {
        this.mDrawHole = enabled;
    }

    /**
     * if true, the white hole inside the chart will be drawn
     */
    private boolean mDrawHole = true;

pieChart.setRotationAngle(0f); //设置旋转的偏移量(以度为单位)。默认270f,也就是到顶部(NORTH)
pieChart.setExtraOffsets(20, 0, 20, 0); //设置要附加到自动计算的偏移的额外偏移(在图表视图周围)。
对应的源码如下:

    /**
     * Sets extra offsets (around the chart view) to be appended to the
     * auto-calculated offsets.
     *
     * @param left
     * @param top
     * @param right
     * @param bottom
     */
    public void setExtraOffsets(float left, float top, float right, float bottom) {
        setExtraLeftOffset(left);
        setExtraTopOffset(top);
        setExtraRightOffset(right);
        setExtraBottomOffset(bottom);
    }

    /**
     * Set an extra offset to be appended to the viewport's left
     */
    public void setExtraLeftOffset(float offset) {
        mExtraLeftOffset = Utils.convertDpToPixel(offset);
    }

    /**
     * Set an extra offset to be appended to the viewport's top
     */
    public void setExtraTopOffset(float offset) {
        mExtraTopOffset = Utils.convertDpToPixel(offset);
    }

    /**
     * Set an extra offset to be appended to the viewport's right
     */
    public void setExtraRightOffset(float offset) {
        mExtraRightOffset = Utils.convertDpToPixel(offset);
    }

    /**
     * Set an extra offset to be appended to the viewport's bottom
     */
    public void setExtraBottomOffset(float offset) {
        mExtraBottomOffset = Utils.convertDpToPixel(offset);
    }

pieChart.setDragDecelerationFrictionCoef(0.95f); //设置减速摩擦系数。减速摩擦系数在[0, 1)之间,较高的值表示速度将缓慢下降,例如,如果设置为0,它将立刻停止。1是无效值,将自动转换为0.999f。
对应的源码如下:

    /**
     * Deceleration friction coefficient in [0 ; 1] interval, higher values
     * indicate that speed will decrease slowly, for example if it set to 0, it
     * will stop immediately. 1 is an invalid value, and will be converted to
     * 0.999f automatically.
     *
     * @param newValue
     */
    public void setDragDecelerationFrictionCoef(float newValue) {

        if (newValue < 0.f)
            newValue = 0.f;

        if (newValue >= 1f)
            newValue = 0.999f;

        mDragDecelerationFrictionCoef = newValue;
    }

    /**
     * Deceleration friction coefficient in [0 ; 1] interval, higher values
     * indicate that speed will decrease slowly, for example if it set to 0, it
     * will stop immediately. 1 is an invalid value, and will be converted to
     * 0.999f automatically.
     */
    private float mDragDecelerationFrictionCoef = 0.9f;

pieChart.setTransparentCircleColor(Color.WHITE); //设置透明圆的颜色
pieChart.setTransparentCircleAlpha(110); //设置透明圆应具有的透明度。0—完全透明,255—完全不透明。默认值为100。
pieChart.setHoleColor(Color.YELLOW); //设置孔的颜色
pieChart.setRotationEnabled(true); //设置为可以触摸旋转,默认为可以触摸旋转
pieChart.setHighlightPerTapEnabled(true); //设置为可以通过点击手势突出显示值
pieChart.highlightValues(null); //突出显示给定DataSet中给定索引处的值。提供null或空数组以撤销所有突出显示。这应该用于以编程方式突出显示值。
pieChart.setDrawEntryLabels(true); //将此属性设置为true可将条目标签绘制到饼图切片中(由PieEntry类的getLabel()方法提供),默认为true。
对应的源码如下:

    /**
     * Set this to true to draw the entry labels into the pie slices (Provided by the getLabel() method of the PieEntry class).
     *
     * @param enabled
     */
    public void setDrawEntryLabels(boolean enabled) {
        mDrawEntryLabels = enabled;
    }

    /**
     * flag indicating if entry labels should be drawn or not
     */
    private boolean mDrawEntryLabels = true;

pieChart.setEntryLabelColor(Color.WHITE); //设置条目标签的颜色
pieChart.setEntryLabelTextSize(8f); //设置条目标签的字体大小
pieChart.setCenterText(“总计:100”); //设置绘制在饼图中心的文字内容
pieChart.setCenterTextColor(Color.YELLOW); //设置绘制在饼图中心的文字颜色
pieChart.setCenterTextSize(20f); //设置绘制在饼图中心的文字大小

我们还可以灵活使用图表图例,我们可以设置图例的位置、图例对应的形状、图例的排列。
具体怎么设置,我们根据所需效果使用Legend的相关方法即可。

上面讲的都是针对饼图UI上进行设置
下面我们来看如何将我们的数据通过饼图展示出来
我们是通过setData(T data)将数据传给pieChart的。先来看一段示例代码:

        List<PieEntry> entries = new ArrayList<PieEntry>();
        for (int i = 0; i < sourceDataList.size(); i++) {
            entries.add(new PieEntry(sourceDataList.get(i).getCounts(), sourceDataList.get(i).getName()));
        }

        PieDataSet dataSet = new PieDataSet(entries, null);  //第二个参数是String类型的label,如果我们不需要label,则传null即可
        dataSet.setSliceSpace(0f);  //设置切片空间
        dataSet.setSelectionShift(5f);  //设置此DataSet的突出显示的饼图切片远离图表中心“移动”的距离,默认为12f
        dataSet.setDrawValues(false);  //不显示百分比

        //数据和颜色。设置饼图中扇区的颜色,按照比例的大小各扇区的颜色依次按照下面定义的(从小到大),如果到达上限后,将重复该顺序。
        int[] colors = new int[]{Color.rgb(255, 194, 77), Color.rgb(254, 137, 42), Color.rgb(227, 85, 73),
                Color.rgb(192, 48, 83), Color.rgb(141, 29, 85), Color.rgb(113, 51, 114),
                Color.rgb(122, 34, 168), Color.rgb(100, 64, 190), Color.rgb(48, 73, 184),
                Color.rgb(0, 135, 221), Color.rgb(58, 151, 255), Color.rgb(1, 137, 176),
                Color.rgb(47, 179, 204), Color.rgb(41, 204, 177), Color.rgb(73, 227, 149),
                Color.rgb(170, 226, 20)};

        dataSet.setColors(colors);
        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);  //设置值的文字大小
        data.setValueTextColor(Color.WHITE);  //设置值的颜色
        pieChart.setData(data);

代码分析:
1、sourceDataList是源数据。
2、我们需要得到一个泛型为PieEntry的集合,然后使用这个集合实例化一个PieDataSet对象。
3、通过PieDataSet对象实例化一个PieData对象。
4、最后我们通过调用setData方法。

当然了,我们还可以设置饼图的动画,通过animateY、animateX、animateXY方法,具体可查看源码(在Chart类中)。

我们还可以给pieChart设置监听器,比如:当我们选中某个扇区的时候,在饼图下方显示对应的描述信息。那我们可以通过:

        pieChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry entry, Highlight highlight) {}

            @Override
            public void onNothingSelected() {}
        });

来实现。

下面再附上两张项目中的真实效果图:
在这里插入图片描述
在这里插入图片描述
这些效果,包括更多的效果,我们都是可以实现的,我们只需根据想要的效果和业务,合理使用上面我们所讲到的api即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值