安卓图形之MPAndroidChart3.0详解二——饼状图

1 前言

饼图和折线图的相关设置和属性差别不大,相同点是:都是通过设置legend(图例)、description(标题)、填充数据等来达到我们想要的效果。但和折线图有差别的就是在饼图中没有yAxis和xAxis,其他大致相同。

2 基本使用
2.1 基础用法

下面这个demo仅仅只是描述了PieChart的基本只用,就只是填充了数据,基本没有设置其他样式
效果图:
>:可以看到,默认的饼图样式为空心圆,且有一点透明圈的感觉。还有旋转和点击放大的效果。
在这里插入图片描述
代码如下:

public class Pie_Frag extends Fragment {

    private PieChart pc;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.pie_frag,null);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        pc = view.findViewById(R.id.pc);

        loadData();

    }

    private void loadData() {
        //设置偏移量
        pc.setExtraOffsets(20,20,20,20);
        //创建数据源List<PieEntry>对象
        List<PieEntry> pieEntries = new ArrayList<PieEntry>();
        
        //添加两个分组
        pieEntries.add(new PieEntry(40f,"有违章"));
        pieEntries.add(new PieEntry(60f,"无违章"));

        PieDataSet pieDataSet = new PieDataSet(pieEntries,"图例标题");
        pieDataSet.setColors(Color.RED,Color.BLUE);//分别为每个分组设置颜色

        PieData pieData = new PieData(pieDataSet);

        //填充数据
        pc.setData(pieData);

    }
}
3 属性介绍
3.1 Description属性

在这里插入图片描述
常用属性

属性注解
setText()设置标题文本
setTextColor()设置标题颜色
setTextSize()设置字体大小
setTypeface()设置字体样式,Typeface枚举值,如加粗等
setTextAlign()设置文本的对齐方式,基本没什么用,一般是通过改变偏移量来设置
setXOffset()设置标题在X轴的偏移量
setYOffset()设置标题在Y轴的偏移量
setPosition()同时设置x和y轴的偏移量
setEnabled()是否启用description,bool值

效果图
在这里插入图片描述
代码如下:

	//该方法在onCreate中直接调用即可,后面会给出完整代码
    private void setdDesc() {
        Description description = new Description();
        description.setText("这是饼图的标题");
        description.setTextColor(Color.RED);
        description.setTextSize(18f);
        description.setTypeface(Typeface.DEFAULT_BOLD);//字体加粗

		// 获取屏幕中间x 轴的像素坐标
        WindowManager wm=(WindowManager)getActivity().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        float x = dm.widthPixels / 2;

        description.setXOffset(x);
        description.setYOffset(50f);
        pc.setDescription(description);
    }
3.2 Legend属性

在这里插入图片描述
常用属性

属性注解
setTextSize()设置图例的文字大小
setTextColor()设置图例文字的颜色
setTypeface()设置字体类型,如加粗
setForm()设置图例形状,默认为方形,LegendForm枚举值
setFormSize()设置图例的大小
setFormLineWidth()设置图例的长度,当图例为线条的时候才生效,其他不生效
setFormToTextSpace()设置图例距离文字的距离,float类型
setVerticalAlignment()设置图例在垂直方向上的对齐方式,LegendVerticalAlignment枚举值
setHorizontalAlignment()设置图例在水平方向上的对齐方式,LegendHorizontalAlignment枚举值
setOrientation()设置图例的排序方式,如水平排列和垂直排列,LegendOrientation枚举值
setDirection()设置图例是在文字的左边还是右边
setXOffset()设置图例在X方向上的偏移量
setYOffset()设置图例在Y方向上的偏移量
setDrawInside()是否将图例绘制在图形内部
setEnabled()设置是否启用Legend,bool值

效果图:
在这里插入图片描述
代码:

	//该方法在onCreate中直接调用即可,后面会给出完整代码
 public void setLegend(){
        Legend legend = pc.getLegend();
        legend.setTextSize(16f);
        legend.setTextColor(Color.BLUE);
        //设置图例是在文字的左边还是右边
        legend.setDirection(Legend.LegendDirection.LEFT_TO_RIGHT);
        //设置图例为圆形,默认为方形
        legend.setOrientation(Legend.LegendOrientation.VERTICAL);
        legend.setForm(Legend.LegendForm.CIRCLE);
        legend.setFormSize(20);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.CENTER);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        legend.setFormToTextSpace(15);
        legend.setXOffset(40);
    }
3.3 PieDataSet属性

PieDataSet是表示的为饼图部分
常用属性

属性注解
setColors()可分别设置每个饼图的颜色,参数为int… colors
setValueTextColor()设置饼图上文字的颜色
setValueTextSize()设置饼图上文字的大小
setValueTypeface()设置饼图上文字的类型,如加粗等
setDrawValues()是否绘制在饼图上的文字,bool类型
setSelectionShift()设置饼块选中时偏离饼图中心的距离
setSliceSpace()设置饼块与饼块之间的距离
setXValuePosition()设置饼图上的文字是绘制在内部还是外部,ValuePosition枚举值
setYValuePosition()用过该属性可以设置是否绘制连接线 ,ValuePosition枚举值
setValueLineVariableLength()设置与饼图的连接线是否可变
setValueLinePart1OffsetPercentage()设置连接线距离饼图的距离,注意为百分数,取值为1-100
setValueLinePart1Length()//设置连接线的长度,一般取0-1的值即可
setValueLineWidth()设置连接线的宽度
setLabel()设置图例的描述
setVisible()设置是否显示饼图形状,bool值
setForm()可以用来设置图例的形状,如圆形
setValueFormatter()自定义文字格式,通过继承IValueFormatter接口实现

在这里插入图片描述
代码如下:

   private void loadData() {
        //设置偏移量
        pc.setExtraOffsets(20,30,20,10);
        //创建数据源List<PieEntry>对象
        List<PieEntry> pieEntries = new ArrayList<PieEntry>();

        //添加两个分组
        pieEntries.add(new PieEntry(40f,"有违章"));
        pieEntries.add(new PieEntry(60f,"无违章"));

        PieDataSet pieDataSet = new PieDataSet(pieEntries,"图例标题");
        pieDataSet.setColors(Color.RED,Color.BLUE);//分别为每个分组设置颜色
//        pieDataSet.setDrawValues();是否绘制文字
        pieDataSet.setValueTextColor(Color.GREEN);//设置在饼图上显示的百分数颜色
        pieDataSet.setSelectionShift(15f);//设置饼块选中时偏离饼图中心的距离
        pieDataSet.setValueTextSize(16f);//设置在饼图上显示文字的大小
        pieDataSet.setValueTypeface(Typeface.DEFAULT_BOLD);
        pieDataSet.setSliceSpace(5f);//设置饼块与饼块之间的距离
        pieDataSet.setValueLineColor(Color.BLUE);//设置连接线的颜色
        //设置饼图上的文字是绘制在内部还是外部
       pieDataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        //可用过该属性可以设置是否绘制连接线
        pieDataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        pieDataSet.setValueLineVariableLength(true);//设置数据连接线的长度是否可变
        //设置连接线距离饼图的距离,注意为百分数,1-100
        pieDataSet.setValueLinePart1OffsetPercentage(80f);
        //设置连接线的长度,一般取0-1的值即可
        pieDataSet.setValueLinePart1Length(0.8f);
        //设置连接线的宽度
        pieDataSet.setValueLineWidth(2f);
        final String strs[] = new String[]{"有违章","无违章"};

        //自定义格式
        pieDataSet.setValueFormatter(new IValueFormatter() {
            private int indd = -1;
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                indd++;
                return strs[indd] + value + "%";
            }
        });

        PieData pieData = new PieData(pieDataSet);

        //填充数据
        pc.setData(pieData);

    }
3.3 PicChart属性

PicChart设置的属性即为整个控件属性
常用属性

属性注解
setExtraOffsets()设置上下左右四个方向的偏移量,也可带个分别设置。可通过该属性来间接改变饼图的大小
setRotation()设置整个控件的旋转角度
setRotationAngle()设置初始旋转角度,没有动画效果
setCenterText()设置显示在饼图中心的文字
setCenterTextSize()设置显示在饼图中心的文字大小
setCenterTextColor()设置显示在饼图中心的文字颜色
setCenterTextTypeface()设置显示在饼图中心的文字类型,如加粗等
setCenterTextSizePixels()设置显示在饼图中心的文字像素,一般大于5才有效果
setCenterTextRadiusPercent()设置中心文字显示的区域,float类型
setCenterTextOffset()设置中心文字在x和y方向上偏移量
setDrawCenterText()是否绘制中间的文本,bool值
setDrawHoleEnabled()是否绘制空洞,若为false则为实心圆,且不会绘制透明圈
setHoleColor()设置空洞的颜色
setHoleRadius()设置空洞的半径大小
setDrawEntryLabels()是否绘制饼图上的文字,注意不是百分比的那个文字
setEntryLabelColor()设置饼图上文字的颜色
setEntryLabelTextSize()设置饼图上文字的大小
setEntryLabelTypeface()设置饼图上文字的类型,如加粗等
setTransparentCircleAlpha()设置透明圈的透明度,默认50%,可通过该属性来达到不显示透明圈的效果
setTransparentCircleRadius()设置透明圈的半径,注意透明圈的半径必须大于空洞的半径,不然看不到效果,默认55%,可通过该属性来达到不显示透明圈的效果
setTransparentCircleColor()设置透明圈的颜色,默认为白色
setTouchEnabled()是否屏蔽所有的手势操作,注意如果设置为false,点击和旋转效果都将不具有
setMaxAngle()通过角度来设置饼图的大小,默认为360,如设置为180的时候只有半个饼图
setUsePercentValues()是否百分比显示,但一般都可以用自定义饼图的文字做到
setRotationEnabled()设置饼图是否可以进行旋转,bool值
setHighlightPerTapEnabled()设置饼图点击某一个饼块是否可以放大,bool值
setBackgroundColor()设置整个饼图的背景颜色
animateXY()设置饼图的动画,一般写两个参数,第一个参数为动画时长,第二个参数为动画类型,一般用Easing.EasingOption.EaseInOutQuad
notifyDataSetChanged()当饼图的数据源发生改变时自动重新填充数据,不需要任何参数

效果图:

完整代码如下


public class Pie_Frag extends Fragment {

    private PieChart pc;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.pie_frag,null);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        pc = view.findViewById(R.id.pc);

        setdDesc();

        loadData();

        setLegend();
    }


    private void setdDesc() {
        Description description = new Description();
        description.setText("这是饼图的标题");
        description.setTextColor(Color.RED);
        description.setTextSize(18f);
        description.setTypeface(Typeface.DEFAULT_BOLD);//字体加粗

		// 获取屏幕中间x 轴的像素坐标
        WindowManager wm=(WindowManager)getActivity().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        float x = dm.widthPixels / 2;

        description.setXOffset(x);
        description.setYOffset(50f);
        pc.setDescription(description);
    }

    public void setLegend(){
        Legend legend = pc.getLegend();
        legend.setTextSize(16f);
        legend.setTextColor(Color.BLUE);
        //设置图例是在文字的左边还是右边
        legend.setDirection(Legend.LegendDirection.LEFT_TO_RIGHT);
        //设置图例为圆形,默认为方形
        legend.setOrientation(Legend.LegendOrientation.VERTICAL);
        legend.setForm(Legend.LegendForm.CIRCLE);
        legend.setFormSize(20);
//        legend.setFormLineWidth(20);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.CENTER);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        legend.setFormToTextSpace(15);
        legend.setXOffset(40);
    }

    private void loadData() {
        //设置偏移量
        pc.setExtraOffsets(20,30,20,10);
        //创建数据源List<PieEntry>对象
        List<PieEntry> pieEntries = new ArrayList<PieEntry>();

        //添加两个分组
        pieEntries.add(new PieEntry(40f,"有违章"));
        pieEntries.add(new PieEntry(60f,"无违章"));

        PieDataSet pieDataSet = new PieDataSet(pieEntries,"图例标题");
        pieDataSet.setColors(Color.RED,Color.BLUE);//分别为每个分组设置颜色
//        pieDataSet.setDrawValues();是否绘制文字
        pieDataSet.setValueTextColor(Color.GREEN);//设置在饼图上显示的百分数颜色
        pieDataSet.setSelectionShift(15f);//设置饼块选中时偏离饼图中心的距离
        pieDataSet.setValueTextSize(16f);//设置在饼图上显示文字的大小
        pieDataSet.setValueTypeface(Typeface.DEFAULT_BOLD);
        pieDataSet.setSliceSpace(5f);//设置饼块与饼块之间的距离

        pieDataSet.setValueLineColor(Color.BLUE);//设置连接线的颜色

        //可用过该属性可以设置是否绘制连接线
        pieDataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        //设置饼图上的文字是绘制在内部还是外部
        pieDataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        pieDataSet.setValueLineVariableLength(true);//设置数据连接线的长度是否可变
        //设置连接线距离饼图的距离,注意为百分数,1-100
        pieDataSet.setValueLinePart1OffsetPercentage(80f);
        //设置连接线的长度,一般取0-1的值即可
        pieDataSet.setValueLinePart1Length(0.8f);
        //设置连接线的宽度
        pieDataSet.setValueLineWidth(2f);

        final String strs[] = new String[]{"有违章","无违章"};

        //自定义格式
        pieDataSet.setValueFormatter(new IValueFormatter() {
            private int indd = -1;
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                indd++;
                if(indd >= strs.length){
                    indd = 0;
                }
                return strs[indd] + value + "%";
            }
        });

        //设置初始旋转角度,没有动画
        pc.setRotationAngle(60f);

        //是否绘制中间的文本
        pc.setDrawCenterText(false);
        pc.setCenterText("中心文字");
        pc.setCenterTextSize(16f);
        pc.setCenterTextColor(Color.BLACK);
        pc.setCenterTextTypeface(Typeface.DEFAULT_BOLD);
        pc.setCenterTextSizePixels(20f);//设置中心显示文字的像素
        //是否绘制空洞,若为false则为实心圆,且不会绘制透明圈
        pc.setDrawHoleEnabled(false);
        //设置空洞的颜色
//        pc.setHoleColor(Color.GRAY);
        //设置空洞的半径大小
//        pc.setHoleRadius(-5f);

        //是否绘制饼图上的文字,不是百分比的那个文字
        pc.setDrawEntryLabels(false);

        //设置透明圈的半径,注意透明圈的半径必须大于空洞的半径,不然看不到效果默认55%
        pc.setTransparentCircleRadius(30f);
        //设置是否可以进行旋转
         pc.setRotationEnabled(false);

         pc.setHighlightPerTapEnabled(false);//设置点击是否可以放大

        pc.animateXY(800,800,Easing.EasingOption.EaseInOutQuad,Easing.EasingOption.EaseInOutQuad);

        PieData pieData = new PieData(pieDataSet);

        //填充数据
        pc.setData(pieData);

    }

}

综合案例

效果图
在这里插入图片描述
上面的描述和下面的框框都是用xml布局实现的

完整代码如下:

xml代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:paddingBottom="10dp"
    android:layout_height="match_parent">

    <TextView
        android:layout_marginTop="20dp"
        android:textSize="22dp"
        android:gravity="center"
        android:textColor="@color/col_pie_bule"
        android:text="有无“重复违章记录的车辆”的占比统计"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <com.github.mikephil.charting.charts.PieChart
        android:id="@+id/pc_test"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:gravity="center"
        android:layout_marginLeft="350dp"
        android:background="@drawable/pie_border"
        android:layout_width="wrap_content"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true"
        android:layout_height="wrap_content">
        <TextView
            android:background="@color/col_pie_bule"
            android:layout_width="25dp"
            android:layout_height="15dp"/>
        <TextView
            android:textSize="18dp"
            android:gravity="center"
            android:textColor="@color/col_pie_bule"
            android:text="无重复违章"
            android:layout_marginLeft="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

        <TextView
            android:layout_marginLeft="20dp"
            android:background="@color/col_pie_red"
            android:layout_width="25dp"
            android:layout_height="15dp"/>
        <TextView
            android:textSize="18dp"
            android:gravity="center"
            android:textColor="@color/col_pie_bule"
            android:text="有重复违章"
            android:layout_marginLeft="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>

</RelativeLayout>

shape代码

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:color="@color/gray" android:width="1dp"/>
    <corners android:radius="10dp"/>
</shape>

Java代码:

public class Pie_test extends Fragment {

    private PieChart pc;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.pie_test,null);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        pc = view.findViewById(R.id.pc_test);

        loadData();

    }

    private void loadData() {

        //不显示描述/标题
        pc.getDescription().setEnabled(false);
        //不显示图例
        pc.getLegend().setEnabled(false);
        //设置上边和下边的偏移量
        pc.setExtraTopOffset(30);
        pc.setExtraBottomOffset(30);
        //数据源
        List<PieEntry> entries = new ArrayList<PieEntry>();
        entries.add(new PieEntry(86.1f));
        entries.add(new PieEntry(13.8f));
        //添加到PieDataSet中
        PieDataSet pieDataSet = new PieDataSet(entries,"");
        pieDataSet.setColors(getResources().getColor(R.color.col_pie_bule),getResources().getColor(R.color.col_pie_red));
        //自定义描述
        final String strs[] = {"无重复违章:","有重复违章:"};

        pieDataSet.setValueFormatter(new IValueFormatter() {
            private int indd = -1;
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                indd ++;
                if(indd >= strs.length){
                    indd = 0;
                }
                return strs[indd] + value + "%";
            }
        });
        //设置饼块之间的间隔
        pieDataSet.setSliceSpace(10f);
        //设置点击某一饼快多出来的距离
        pieDataSet.setSelectionShift(15f);
        //设置连接线显示在外面
        pieDataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        //设置连接线距离饼图的距离,为百分数
        pieDataSet.setValueLinePart1OffsetPercentage(100f);
        //定义连接线的长度
        pieDataSet.setValueLinePart1Length(0.7f);
        
        //不绘制空洞
        pc.setDrawHoleEnabled(false);
        //不可旋转
        pc.setRotationEnabled(false);
        PieData pieData = new PieData(pieDataSet);
        //设置数据
        pc.setData(pieData);


    }


}
  • 8
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值