Android 图表开源框架之MPAndroidChart LineChart折线图(二)

Android 图表开源框架之MPAndroidChart LineChart之常用自定义设置功能

      Android 图表开源框架之MPAndroidChart LineChart折线图,v3.0.1版本,MPAndroidChart是一款基于Android的开源图表库,MPAndroidChart不仅可以在Android设备上绘制各种统计图表,而且可以对图表进行拖动和缩放操作,应用起来非常灵活。MPAndroidChart显得更为轻巧和简单,拥有常用的图表类型:线型图、饼图、柱状图和散点图。

效果图:

一.简单实现:

1.添加依赖:

dependencies {    implementation fileTree(dir: 'libs', include: ['*.jar'])//    implementation 'com.android.support:appcompat-v7:29.+'    implementation 'com.android.support:appcompat-v7:28.0.0'    implementation 'com.android.support.constraint:constraint-layout:1.1.3'    testImplementation 'junit:junit:4.12'    androidTestImplementation 'com.android.support.test:runner:1.0.2'    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'    implementation 'com.github.PhilJay:MPAndroidChart:v3.0.1'//    implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'}
allprojects {    repositories {        google()        jcenter()        maven { url "https://jitpack.io" }    }}

2.主函数:

import android.annotation.SuppressLint;import android.content.Context;import android.graphics.Color;import android.graphics.DashPathEffect;import android.graphics.Typeface;import android.support.v4.content.ContextCompat;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.text.format.DateFormat;import android.util.DisplayMetrics;import android.view.MotionEvent;import android.view.View;import android.view.WindowManager;import com.example.m1571.mympandroidchart.utils.CustomXValueFormatter;import com.example.m1571.mympandroidchart.utils.MyMarkerView;import com.github.mikephil.charting.animation.Easing;import com.github.mikephil.charting.charts.LineChart;import com.github.mikephil.charting.charts.PieChart;import com.github.mikephil.charting.components.AxisBase;import com.github.mikephil.charting.components.Description;import com.github.mikephil.charting.components.Legend;import com.github.mikephil.charting.components.LimitLine;import com.github.mikephil.charting.components.XAxis;import com.github.mikephil.charting.components.YAxis;import com.github.mikephil.charting.data.Entry;import com.github.mikephil.charting.data.LineData;import com.github.mikephil.charting.data.LineDataSet;import com.github.mikephil.charting.data.PieData;import com.github.mikephil.charting.data.PieDataSet;import com.github.mikephil.charting.data.PieEntry;import com.github.mikephil.charting.formatter.IAxisValueFormatter;import com.github.mikephil.charting.formatter.PercentFormatter;import com.github.mikephil.charting.highlight.Highlight;import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;import com.github.mikephil.charting.listener.OnChartValueSelectedListener;import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Random;import java.util.Set;/** * * 图表开源框架 * https://blog.csdn.net/qq_43332570/article/details/103180779 * *https://blog.csdn.net/qq_26787115/article/details/53611373 * * * https://www.jb51.net/article/142778.htm * https://www.jb51.net/article/141344.htm * https://www.jb51.net/article/96508.htm * 

* https://github.com/hdodenhof/CircleImageView */public class MainActivity extends AppCompatActivity { ArrayList pieEntryList = new ArrayList();//数据列表 ArrayList colors = new ArrayList();//颜色列表 private LineChart lineChart; float datas[] = {14f,15f,16f,17f,16f,16f}; float datas2[] = {17f,16f,15f,14f,17f,14f}; //在MPAndroidChart一般都是通过List对象来装数据的 final List entries = new ArrayList(); final List entries2 = new ArrayList(); final List yRightList = new ArrayList(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //渐变圆环 CircleProgressBar color_progress_view = (CircleProgressBar) findViewById(R.id.color_progress_view); color_progress_view.setMaxStepNum(500); color_progress_view.update(470, 2000); // //扇形图 final PieChart mChart = (PieChart) findViewById(R.id.chart1); lineChart = (LineChart) findViewById(R.id.lineChart);// initLineChart(); //曲线图 折线图 setData(); // 设置周围字体颜色 mChart.setCenterTextColor(Color.BLACK); HashMap dataMap = new HashMap(); dataMap.put("Ⅰ类水", "8"); dataMap.put("Ⅱ类水", "12"); dataMap.put("Ⅲ类水", "31"); dataMap.put("Ⅳ类水", "24"); dataMap.put("Ⅴ类水", "10"); dataMap.put("劣Ⅴ类水", "15"); PieChartUtil.getPitChart().setPieChart(mChart, dataMap, "水质", true); //点击事件 mChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() { @Override public void onValueSelected(Entry e, Highlight h) { PieEntry pieEntry = (PieEntry) e; mChart.setCenterText(pieEntry.getLabel()); } @Override public void onNothingSelected() { } });// mChart.getDescription().setEnabled(false); //设置pieChart图表的描述// mChart.setBackgroundColor(Color.WHITE); //设置pieChart图表背景色// mChart.setRotationEnabled(true);//可以手动旋转// mChart.setDragDecelerationFrictionCoef(0.95f);//设置pieChart图表转动阻力摩擦系数[0,1]// mChart.setHighlightPerTapEnabled(true); //设置piecahrt图表点击Item高亮是否可用// mChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);// 设置pieChart图表展示动画效果// Legend l = mChart.getLegend();// l.setEnabled(true); //是否启用图列(true:下面属性才有意义// l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);// l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);// l.setOrientation(Legend.LegendOrientation.VERTICAL);// l.setForm(Legend.LegendForm.DEFAULT); //设置图例的形状// l.setFormSize(10); //设置图例的大小// l.setFormToTextSpace(10f); //设置每个图例实体中标签和形状之间的间距// l.setDrawInside(false);// l.setWordWrapEnabled(true); //设置图列换行(注意使用影响性能,仅适用legend位于图表下面)// l.setXEntrySpace(10f); //设置图例实体之间延X轴的间距(setOrientation = HORIZONTAL有效)// l.setYEntrySpace(8f); //设置图例实体之间延Y轴的间距(setOrientation = VERTICAL 有效)// l.setYOffset(0f); //设置比例块Y轴偏移量// l.setTextSize(14f); //设置图例标签文本的大小// l.setTextColor(Color.parseColor("#333333"));//设置图例标签文本的颜色// for (int i = 0; i < pieEntryList.size(); i++) {//list为数据列表// Random random = new Random();// int r = random.nextInt(256);// int g = random.nextInt(256);// int b = random.nextInt(256);// colors.add(Color.rgb(r,g,b));// pieEntryList.add(new PieEntry(Float.parseFloat(townsChartEntity.getRecordSet0().getR().get(i).getC().get(2)) * 100 / all, townsChartEntity.getRecordSet0().getR().get(i).getC().get(1)));// }// //饼状图数据集 PieDataSet// PieDataSet pieDataSet = new PieDataSet(pieEntryList, "图表名称");// pieDataSet.setSliceSpace(3f); //设置饼状Item之间的间隙// pieDataSet.setSelectionShift(30f); //设置饼状Item被选中时变化的距离// pieDataSet.setColors(colors); //为DataSet中的数据匹配上颜色集(饼图Item颜色)// //最终数据 PieData// PieData pieData = new PieData(pieDataSet);// pieData.setDrawValues(true); //设置是否显示数据实体(百分比,true:以下属性才有意义)// pieData.setValueTextColor(Color.BLUE); //设置所有DataSet内数据实体(百分比)的文本颜色// pieData.setValueTextSize(12f); //设置所有DataSet内数据实体(百分比)的文本字体大小// pieData.setValueFormatter(new PercentFormatter());//设置所有DataSet内数据实体(百分比)的文本字体格式//// mChart.setData(pieData);// mChart.highlightValues(null);// mChart.invalidate(); //将图表重绘以显示设置的属性和数据// PieData mPieData = getPieData(4, 100);// showChart(mChart, mPieData); //模拟数据// HashMap dataMap = new HashMap();// dataMap.put("A","300");// dataMap.put("B","600");// dataMap.put("C","500");// dataMap.put("D","800");//// setPieChart(mChart,dataMap,"数据",true); } public void setData(){ yRightList.add("QQ"); yRightList.add("SS"); yRightList.add("VB"); yRightList.add("FF"); //循环取出数据 for(int i = 0; i < datas.length; i++){ entries.add(new Entry(i,datas[i])); } //循环取出数据 for(int i = 0; i < datas2.length; i++){ entries2.add(new Entry(i,datas2[i])); } //得到X轴 XAxis xAxis = lineChart.getXAxis(); //设置X轴的位置(默认在上方) xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); //不显示网格线 xAxis.setDrawGridLines(false); //得到Y轴 YAxis yAxis = lineChart.getAxisLeft(); YAxis rightYAxis = lineChart.getAxisRight(); YAxis leftYAxis = lineChart.getAxisLeft(); //设置Y轴是否显示 rightYAxis.setEnabled(false); //右侧Y轴不显示// leftYAxis.setEnabled(false); //左侧Y轴不显示 // 标签倾斜 xAxis.setLabelRotationAngle(45);// setDesc();// setLegend(); setXAxis(); setYAxis(); // 不显示数据描述 lineChart.getDescription().setEnabled(false); // 没有数据的时候,显示“暂无数据” lineChart.setNoDataText("暂无数据"); // 不显示表格颜色 lineChart.setDrawGridBackground(false); // 不可以缩放 lineChart.setScaleEnabled(false); // 不显示y轴右边的值// lineChart.getAxisRight().setEnabled(false); //设置X轴值为字符串// xAxis.setValueFormatter(new IAxisValueFormatter() {// @Override// public String getFormattedValue(float value, AxisBase axis) {// int IValue = (int) value;// CharSequence format = DateFormat.format("MM/dd",// System.currentTimeMillis() - (long) (entries.size() - IValue) * 24 * 60 * 60 * 1000);// return format.toString();// }// }); //一个LineDataSet对象就是一条曲线 LineDataSet lineDataSet = new LineDataSet(entries,"第一条数据"); LineDataSet lineDataSet2 = new LineDataSet(entries2,"第二条数据");// lineDataSet.setForm(Legend.LegendForm.LINE);// lineDataSet.setFormLineWidth(10f);//只有lineDataSet.setForm(Legend.LegendForm.LINE);时才有作用 这里我们设置的是圆所以这句代码直接注释// lineDataSet.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));//设置虚线,只有lineDataSet.setForm(Legend.LegendForm.LINE);时才有作用 lineDataSet2.setColor(Color.BLUE);//设置曲线的颜色// lineDataSet.setFillColor(Color.GRAY);//设置线条下方的填充 //设置显示曲线下方的背景色// lineDataSet.setDrawFilled(true); //给曲线下方设置渐变色的阴影// lineDataSet.setFillDrawable(getResources().getDrawable(R.drawable.line_gradient_bg_shape));//设置线条下方的填充 //折线图点的标记 MyMarkerView mv = new MyMarkerView(this); lineChart.setMarker(mv); //保存LineDataSet集合 ArrayList dataSets = new ArrayList<>(); dataSets.add(lineDataSet); // add the datasets dataSets.add(lineDataSet2); //LineData才是正真给LineChart的数据// LineData lineData = new LineData(lineDataSet);//一条曲线 LineData lineData = new LineData(dataSets);//多条曲线 lineChart.setData(lineData); // animateX(int durationMillis) : 水平轴动画 在指定时间内 从左到右// animateY(int durationMillis) : 垂直轴动画 从下到上// animateXY(int xDuration, int yDuration) : 两个轴动画,从左到右,从下到上// lineChart.animateXY(1000,1000); lineChart.animateX(1000); } public void setDesc(){ Description description = new Description(); description.setText("这是折线图的标题");//设置文本 description.setTextSize(22f); //设置文本大小 description.setTypeface(Typeface.DEFAULT_BOLD);//设置文本样式加粗显示 description.setTextColor(Color.RED);//设置文本颜色 //获取屏幕的中间位置 WindowManager wm=(WindowManager)getSystemService(Context.WINDOW_SERVICE); DisplayMetrics dm = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(dm); float x = dm.widthPixels / 2; description.setPosition(x,40);//设置文本的位置 lineChart.setDescription(description);//添加给LineChart } public void setLegend(){ //为了让大家更直观的看到效果,我这里设置了整个图形距离上下左右四个方向的边距 //在后面会讲解 lineChart.setExtraOffsets(30,60,30,30); //得到Legend对象 Legend legend = lineChart.getLegend(); legend.setDrawInside(false);//不绘制在图形内部 legend.setTextSize(38f);//设置文字大小 legend.setTypeface(Typeface.DEFAULT_BOLD);//文字加粗 legend.setFormSize(50f);//设置图例的大小 legend.setTextColor(Color.BLUE);//设置文字颜色 legend.setFormToTextSpace(20f);//设置图例距离文字的距离 legend.setForm(Legend.LegendForm.LINE);//设置图例类型为线条 legend.setYOffset(20f);//距离底部20dp //设置图例下、中对齐 legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM); legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER); } //此方法在onCreate中直接调用即可, 下方会给出完整代码 public void setYAxis(){ //不显示右侧的Y轴 lineChart.getAxisRight().setEnabled(true); lineChart.getAxisLeft().setEnabled(true); YAxis yAxis = lineChart.getAxisRight(); YAxis yAxisL = lineChart.getAxisLeft(); //右侧Y轴数据设置// yAxis.setLabelCount(7,true);//显示7个// yAxis.setAxisMaximum(19f);//设置最大值// yAxis.setAxisMinimum(9f);//设置最小值 yAxis.setTextSize(14f);//设置文本大小 yAxis.setXOffset(15);//设置15dp的距离 yAxis.setDrawAxisLine(false);//设置左侧Y线不显示 yAxis.setLabelCount(4,true);//设置Y轴显示多少个点 yAxis.setAxisMaximum(17f);//设置左侧Y轴最大值 yAxis.setAxisMinimum(14f);//设置左侧Y轴最小值 //左侧Y轴数据设置 yAxisL.setTextSize(14f);//设置文本大小 yAxisL.setXOffset(15);//设置15dp的距离 yAxisL.setDrawAxisLine(false);//设置左侧Y线不显示 yAxisL.setLabelCount(4,true);//设置Y轴显示多少个点 yAxisL.setAxisMaximum(17f);//设置左侧Y轴最大值 yAxisL.setAxisMinimum(14f);//设置左侧Y轴最小值// LimitLine ll2 = new LimitLine(8f, "");// ll2.setLineWidth(3f);// ll2.setLineColor(ContextCompat.getColor(this, android.R.color.black));// ll2.enableDashedLine(5f, 5f, 0f);//虚线// ll2.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);//设置标签显示的位置// ll2.setTextColor(ContextCompat.getColor(this, android.R.color.background_dark));// ll2.setTextSize(10f);// yAxis.setInverted(false);// yAxis.setGridLineWidth(2);//设置分割线宽度 //自定义格式// yAxis.setValueFormatter(new IAxisValueFormatter() {// @Override// public String getFormattedValue(float value, AxisBase axis) { if(value == 9){ return "(S)"; }// ArrayList arrayList = new ArrayList<>();// arrayList.add("中国");// arrayList.add("中国1");// arrayList.add("中国2");// arrayList.add("中国3");// arrayList.add("中国4");// String tep = null;// for (int i = 0; i < arrayList.size(); i++) {// tep = arrayList.get(i) + "";// } String tep = value + ""; return tep.substring(0,tep.indexOf(".")) + "℃";// return tep;// }// }); //设置左侧Y轴的数据 yAxisL.setValueFormatter(new CustomXValueFormatter(yRightList)); } public void setXAxis() { XAxis xAxis = lineChart.getXAxis(); xAxis.setTextSize(14f);//设置字体大小 xAxis.setTextColor(Color.RED);//设置字体颜色 xAxis.setLabelRotationAngle(60f);//旋转60度 xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//将x轴位于底部 xAxis.setDrawGridLines(false);//不绘制网格线 xAxis.setGranularity(1);//间隔1 //小技巧,通过设置Axis的最小值设置为负值 //可以改变距离与Y轴的距离 final String weeks[] = {"昨天","今天","明天","周五","周六","周日"}; xAxis.setAxisMaximum(5.2f);//设置最小值 xAxis.setAxisMinimum(-0.2f);//设置最大值 xAxis.setLabelCount(weeks.length);//设置数量 xAxis.setTextColor(Color.BLACK); //自定义样式 xAxis.setValueFormatter(new IAxisValueFormatter() { @Override public String getFormattedValue(float value, AxisBase axis) { return weeks[(int) value]; } }); } private void initLineChart() { List arrayList = new ArrayList<>(); arrayList.add(90); arrayList.add(90); arrayList.add(90); arrayList.add(90); arrayList.add(90); initLineChart(arrayList); }/** * 初始化曲线图表 * * @param list 数据集 */ private void initLineChart(final List list) { //显示边界 lineChart.setDrawBorders(false); //设置数据 List entries = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { entries.add(new Entry(i, (float) list.get(i))); } //一个LineDataSet就是一条线 LineDataSet lineDataSet = new LineDataSet(entries, ""); //线颜色 lineDataSet.setColor(Color.parseColor("#F15A4A")); //线宽度 lineDataSet.setLineWidth(1.6f); //不显示圆点 lineDataSet.setDrawCircles(false); //线条平滑 lineDataSet.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER); //设置折线图填充// lineDataSet.setDrawFilled(true); LineData data = new LineData(lineDataSet); //无数据时显示的文字 lineChart.setNoDataText("暂无数据"); //折线图不显示数值 data.setDrawValues(false); //得到X轴 XAxis xAxis = lineChart.getXAxis(); //设置X轴的位置(默认在上方) xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); //设置X轴坐标之间的最小间隔 xAxis.setGranularity(1f); //设置X轴的刻度数量,第二个参数为true,将会画出明确数量(带有小数点),但是可能值导致不均匀,默认(6,false) xAxis.setLabelCount(list.size() / 6, false); //设置X轴的值(最小值、最大值、然后会根据设置的刻度数量自动分配刻度显示) xAxis.setAxisMinimum(0f); xAxis.setAxisMaximum((float) list.size()); //不显示网格线 xAxis.setDrawGridLines(false); // 标签倾斜 xAxis.setLabelRotationAngle(45); //设置X轴值为字符串 xAxis.setValueFormatter(new IAxisValueFormatter() { @Override public String getFormattedValue(float value, AxisBase axis) { int IValue = (int) value; CharSequence format = DateFormat.format("MM/dd", System.currentTimeMillis() - (long) (list.size() - IValue) * 24 * 60 * 60 * 1000); return format.toString(); } }); //得到Y轴 YAxis yAxis = lineChart.getAxisLeft(); YAxis rightYAxis = lineChart.getAxisRight(); //设置Y轴是否显示 rightYAxis.setEnabled(false); //右侧Y轴不显示 //设置y轴坐标之间的最小间隔 //不显示网格线 yAxis.setDrawGridLines(false); //设置Y轴坐标之间的最小间隔 yAxis.setGranularity(1); //设置y轴的刻度数量 //+2:最大值n就有n+1个刻度,在加上y轴多一个单位长度,为了好看,so+2 yAxis.setLabelCount(Collections.max(list) + 2, false); //设置从Y轴值 yAxis.setAxisMinimum(0f); //+1:y轴多一个单位长度,为了好看 yAxis.setAxisMaximum(Collections.max(list) + 1); //y轴 yAxis.setValueFormatter(new IAxisValueFormatter() { @Override public String getFormattedValue(float value, AxisBase axis) { int IValue = (int) value; return String.valueOf(IValue); } }); //图例:得到Lengend Legend legend = lineChart.getLegend(); //隐藏Lengend legend.setEnabled(false); //隐藏描述 Description description = new Description(); description.setEnabled(false); lineChart.setDescription(description); //折线图点的标记 MyMarkerView mv = new MyMarkerView(this); lineChart.setMarker(mv); //设置数据 lineChart.setData(data); //图标刷新 lineChart.invalidate(); //解决滑动冲突 lineChart.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: {// scrollview.requestDisallowInterceptTouchEvent(true); break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: {// scrollview.requestDisallowInterceptTouchEvent(false); break; } } return false; } }); } //设置各区块的颜色 public static final int[] PIE_COLORS = { Color.rgb(181, 194, 202), Color.rgb(129, 216, 200), Color.rgb(241, 214, 145), Color.rgb(108, 176, 223), Color.rgb(195, 221, 155), Color.rgb(251, 215, 191), Color.rgb(237, 189, 189), Color.rgb(172, 217, 243) }; //设置饼形图属性 public void setPieChart(PieChart pieChart, Map pieValues, String title, boolean showLegend) { pieChart.setUsePercentValues(true);//设置使用百分比(后续有详细介绍) pieChart.getDescription().setEnabled(false);//设置描述 pieChart.setExtraOffsets(25, 10, 25, 25); //设置边距 pieChart.setDragDecelerationFrictionCoef(0.95f);//设置摩擦系数(值越小摩擦系数越大) pieChart.setCenterText(title);//设置环中的文字 pieChart.setRotationEnabled(true);//是否可以旋转 pieChart.setHighlightPerTapEnabled(true);//点击是否放大 pieChart.setCenterTextSize(22f);//设置环中文字的大小 pieChart.setDrawCenterText(true);//设置绘制环中文字 pieChart.setRotationAngle(120f);//设置旋转角度 pieChart.setTransparentCircleRadius(61f);//设置半透明圆环的半径,看着就有一种立体的感觉 //这个方法为true就是环形图,为false就是饼图 pieChart.setDrawHoleEnabled(false); //设置环形中间空白颜色是白色 pieChart.setHoleColor(Color.WHITE); //设置半透明圆环的颜色 pieChart.setTransparentCircleColor(Color.WHITE); //设置半透明圆环的透明度 pieChart.setTransparentCircleAlpha(110); //图例设置 Legend legend = pieChart.getLegend(); if (showLegend) { legend.setEnabled(true);//是否显示图例 legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);//图例相对于图表横向的位置 legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);//图例相对于图表纵向的位置 legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);//图例显示的方向 legend.setDrawInside(false); legend.setDirection(Legend.LegendDirection.LEFT_TO_RIGHT); } else { legend.setEnabled(false); } //设置饼图数据 setPieChartData(pieChart, pieValues); pieChart.animateX(1500, Easing.EasingOption.EaseInOutQuad);//数据显示动画 } //设置饼图数据 private void setPieChartData(PieChart pieChart, Map pieValues) { ArrayList xValues = new ArrayList(); //xVals用来表示每个饼块上的内容 for (int i = 0; i < 4; i++) { xValues.add("Quarterly" + (i + 1)); //饼块上显示成Quarterly1, Quarterly2, Quarterly3, Quarterly4 } ArrayList yValues = new ArrayList(); //yVals用来表示封装每个饼块的实际数据// 饼图数据 /** * 将一个饼形图分成四部分, 四部分的数值比例为14:14:34:38 * 所以 14代表的百分比就是14% */ float quarterly1 = 14; float quarterly2 = 14; float quarterly3 = 34; float quarterly4 = 38; yValues.add(new Entry(quarterly1, 0)); yValues.add(new Entry(quarterly2, 1)); yValues.add(new Entry(quarterly3, 2)); yValues.add(new Entry(quarterly4, 3));// Set set = pieValues.entrySet();// Iterator it = set.iterator();// while (it.hasNext()) {// Map.Entry entry = (Map.Entry) it.next();// entries.add(new PieEntry(Float.valueOf(entry.getValue().toString()), entry.getKey().toString()));// } PieDataSet dataSet = new PieDataSet(yValues, ""); dataSet.setSliceSpace(3f);//设置饼块之间的间隔 dataSet.setSelectionShift(5f);//设置饼块选中时偏离饼图中心的距离 dataSet.setColors(PIE_COLORS);//设置饼块的颜色 //设置数据显示方式有见图 dataSet.setValueLinePart1OffsetPercentage(80f);//数据连接线距图形片内部边界的距离,为百分数 dataSet.setValueLinePart1Length(0.3f); dataSet.setValueLinePart2Length(0.4f); dataSet.setValueLineColor(Color.YELLOW);//设置连接线的颜色 dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE); PieData pieData = new PieData(dataSet); pieData.setValueFormatter(new PercentFormatter()); pieData.setValueTextSize(11f); pieData.setValueTextColor(Color.DKGRAY); pieChart.setData(pieData); pieChart.highlightValues(null); pieChart.invalidate(); } private void initPieChart() {// PieChart mChart = (PieChart) findViewById(R.id.spread_pie_chart);// PieData mPieData = getPieData(4, 100);// showChart(mChart, mPieData); } private void showChart(PieChart pieChart, PieData pieData) {// pieChart.setHoleColorTransparent(true); pieChart.setHoleRadius(60f); //半径 pieChart.setTransparentCircleRadius(64f); // 半透明圈//pieChart.setHoleRadius(0); //实心圆// pieChart.setDescription("测试饼状图");// mChart.setDrawYValues(true); pieChart.setDrawCenterText(true); //饼状图中间可以添加文字 pieChart.setDrawHoleEnabled(true); pieChart.setRotationAngle(90); // 初始旋转角度// draws the corresponding description value into the slice// mChart.setDrawXValues(true);// enable rotation of the chart by touch pieChart.setRotationEnabled(true); // 可以手动旋转// display percentage values pieChart.setUsePercentValues(true); //显示成百分比// mChart.setUnit(" €");// mChart.setDrawUnitsInChart(true);// add a selection listener// mChart.setOnChartValueSelectedListener(this);// mChart.setTouchEnabled(false);// mChart.setOnAnimationListener(this); pieChart.setCenterText("Quarterly Revenue"); //饼状图中间的文字//设置数据 pieChart.setData(pieData);// undo all highlights// pieChart.highlightValues(null);// pieChart.invalidate(); Legend mLegend = pieChart.getLegend(); //设置比例图 mLegend.setPosition(Legend.LegendPosition.RIGHT_OF_CHART); //最右边显示// mLegend.setForm(LegendForm.LINE); //设置比例图的形状,默认是方形 mLegend.setXEntrySpace(7f); mLegend.setYEntrySpace(5f);// Legend l = mChart.getLegend();// l.setEnabled(true); //是否启用图列(true:下面属性才有意义// l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);// l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);// l.setOrientation(Legend.LegendOrientation.VERTICAL);// l.setForm(Legend.LegendForm.DEFAULT); //设置图例的形状// l.setFormSize(10); //设置图例的大小// l.setFormToTextSpace(10f); //设置每个图例实体中标签和形状之间的间距// l.setDrawInside(false);// l.setWordWrapEnabled(true); //设置图列换行(注意使用影响性能,仅适用legend位于图表下面)// l.setXEntrySpace(10f); //设置图例实体之间延X轴的间距(setOrientation = HORIZONTAL有效)// l.setYEntrySpace(8f); //设置图例实体之间延Y轴的间距(setOrientation = VERTICAL 有效)// l.setYOffset(0f); //设置比例块Y轴偏移量// l.setTextSize(14f); //设置图例标签文本的大小// l.setTextColor(Color.parseColor("#333333"));//设置图例标签文本的颜色 pieChart.animateXY(1000, 1000); //设置动画// mChart.spin(2000, 0, 360); } /** * @param count 分成几部分 * @param range */ private PieData getPieData(int count, float range) { ArrayList xValues = new ArrayList(); //xVals用来表示每个饼块上的内容 for (int i = 0; i < count; i++) { xValues.add("Quarterly" + (i + 1)); //饼块上显示成Quarterly1, Quarterly2, Quarterly3, Quarterly4 } ArrayList yValues = new ArrayList(); //yVals用来表示封装每个饼块的实际数据// 饼图数据 /** * 将一个饼形图分成四部分, 四部分的数值比例为14:14:34:38 * 所以 14代表的百分比就是14% */ float quarterly1 = 14; float quarterly2 = 14; float quarterly3 = 34; float quarterly4 = 38; yValues.add(new Entry(quarterly1, 0)); yValues.add(new Entry(quarterly2, 1)); yValues.add(new Entry(quarterly3, 2)); yValues.add(new Entry(quarterly4, 3)); //y轴的集合 PieDataSet pieDataSet = new PieDataSet(yValues, "Quarterly Revenue 2014"/*显示在比例图上*/); pieDataSet.setSliceSpace(0f); //设置个饼状图之间的距离 ArrayList colors = new ArrayList();// 饼图颜色 colors.add(Color.rgb(205, 205, 205)); colors.add(Color.rgb(114, 188, 223)); colors.add(Color.rgb(255, 123, 124)); colors.add(Color.rgb(57, 135, 200)); pieDataSet.setColors(colors); DisplayMetrics metrics = getResources().getDisplayMetrics(); float px = 5 * (metrics.densityDpi / 160f); pieDataSet.setSelectionShift(px); // 选中态多出的长度// PieData pieData = new PieData(xValues, pieDataSet); PieData pieData = new PieData(pieDataSet); pieData.setDrawValues(true); return pieData; }}

2.主函数布局:(请忽略其它的自定义控件)

<?xml version="1.0" encoding="utf-8"?>                                                                                        

 3.自定义MyMarkerView提示内容框:

import android.content.Context;import android.text.format.DateFormat;import android.widget.TextView;import com.example.m1571.mympandroidchart.R;import com.github.mikephil.charting.components.MarkerView;import com.github.mikephil.charting.data.Entry;import com.github.mikephil.charting.highlight.Highlight;import com.github.mikephil.charting.utils.MPPointF;import java.text.DecimalFormat;public class MyMarkerView extends MarkerView{    private TextView tvContent;    private DecimalFormat format = new DecimalFormat("##0");    public MyMarkerView(Context context) {        super(context, R.layout.layout_markerview);//这个布局自己定义        tvContent = (TextView) findViewById(R.id.tvContent);    }    //显示的内容    @Override    public void refreshContent(Entry e, Highlight highlight) {//        tvContent.setText(format(e.getX())+"\n"+format.format(e.getY())+"辆");        tvContent.setText(format.format(e.getY())+"辆");        super.refreshContent(e, highlight);    }    //标记相对于折线图的偏移量    @Override    public MPPointF getOffset() {        return new MPPointF(-(getWidth() / 2), -getHeight());    }    //时间格式化(显示今日往前30天的每一天日期)    public String  format(float x)    {        CharSequence format = DateFormat.format("MM月dd日",                System.currentTimeMillis()-(long) (30-(int)x)*24*60*60*1000);        return format.toString();    }}

4.layout_markerview.xml布局:

<?xml version="1.0" encoding="utf-8"?>                

5.背景色:bg_shape_c.xml

<?xml version="1.0" encoding="utf-8"?>            

6.参考案例:

https://github.com/897532167/ChartManager

 https://github.com/PhilJay/MPAndroidChart

https://github.com/lecho/hellocharts-android

https://github.com/JinBoy23520/MPAndroidChartDemoByJin

https://blog.csdn.net/qq_43332570/article/details/103180779

https://blog.csdn.net/xiehuimx/article/details/51731649

https://blog.csdn.net/dt235201314/article/details/56841839

https://blog.csdn.net/y1010012836/article/details/88532938?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-4.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-4.nonecase

https://blog.csdn.net/cf8833/article/details/80076175

https://www.jb51.net/article/91174.htm

https://blog.csdn.net/cf8833/article/details/79987051?utm_medium=distribute.pc_relevant.none-task-blog-baidujs-4

https://blog.csdn.net/StramChen/article/details/89875600?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase

https://blog.csdn.net/Dr_abandon/article/details/88819160?utm_medium=distribute.pc_relevant.none-task-blog-baidujs-1

更多相关文章

  1. android:gravity
  2. 设置textview的字体
  3. Android(安卓)Theme的设置
  4. android:id="@+id/android:empty属性的用法举例
  5. android中的数据库操作
  6. android 写 xml时,加layout与不加的区别(如layout_gravity与gravit
  7. Android中自定义shape
  8. 【Android布局】在程序中设置android:gravity 和 android:layout
  9. Android数据加密之Rsa加密

随机推荐

  1. android本地分享
  2. phonegap hardwareAccelerated问题
  3. app安装位置声明
  4. Android(安卓)每隔3s更新一次title
  5. Android(安卓)HOME键的屏蔽
  6. android 中RectF构造函数参数说明
  7. Android之获取移动网络ip
  8. Android注解式绑定控件BindView
  9. xbmc接受遥控键值并生成 XBMC_Event的过
  10. Android(安卓)Shape的使用