Android图表 MPAndroidChart折线图

MadisonCamp 7年前
   <p style="text-align:center"><img src="https://simg.open-open.com/show/eaa65fd80e4d449f7e472957c872f9a8.png"></p>    <p style="text-align:center">封面</p>    <h2>1.介绍</h2>    <p>MPAndroidChart的强大之处就不在多说了,目前最新的版本是3.0.1,在新版本中很多方法都被弃用了,这个要注意一下,在网上查到的大多数资料都是关于旧版本的,今天来实现一下折线图,把过程记录下来,分享给大家。</p>    <p>效果图:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/3143fcb0d0ab4b0cd7941f307a9833ba.gif"></p>    <p style="text-align:center">折线图</p>    <h2>2.引入开源库</h2>    <ul>     <li>在项目根目录的build.gradle文件中加入如下代码</li>    </ul>    <pre>  <code class="language-java">allprojects {      repositories {          maven { url "https://jitpack.io" }      }  }</code></pre>    <ul>     <li>在app根目录的buil.gradle文件中加入依赖</li>    </ul>    <pre>  <code class="language-java">dependencies {      compile 'com.github.PhilJay:MPAndroidChart:v3.0.1'  }</code></pre>    <h2>3.实现</h2>    <p>在项目中,我把图表相关的功能抽取成了一个工具类ChartUtils。</p>    <h2>初始化图表</h2>    <p>initChart方法用来设置图表的功能和显示的样式,方法中注释了缩放和动画的代码,如果要使用动画,则不需要调用图表的invalidate方法。</p>    <pre>  <code class="language-java">/**   * 初始化图表   *   * @param chart 原始图表   * @return 初始化后的图表   */  public static LineChart initChart(LineChart chart) {      // 不显示数据描述      chart.getDescription().setEnabled(false);      // 没有数据的时候,显示“暂无数据”      chart.setNoDataText("暂无数据");      // 不显示表格颜色      chart.setDrawGridBackground(false);      // 不可以缩放      chart.setScaleEnabled(false);      // 不显示y轴右边的值      chart.getAxisRight().setEnabled(false);      // 不显示图例      Legend legend = chart.getLegend();      legend.setEnabled(false);      // 向左偏移15dp,抵消y轴向右偏移的30dp      chart.setExtraLeftOffset(-15);        XAxis xAxis = chart.getXAxis();      // 不显示x轴      xAxis.setDrawAxisLine(false);      // 设置x轴数据的位置      xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);      xAxis.setTextColor(Color.WHITE);      xAxis.setTextSize(12);      xAxis.setGridColor(Color.parseColor("#30FFFFFF"));      // 设置x轴数据偏移量      xAxis.setYOffset(-12);        YAxis yAxis = chart.getAxisLeft();      // 不显示y轴      yAxis.setDrawAxisLine(false);      // 设置y轴数据的位置      yAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);      // 不从y轴发出横向直线      yAxis.setDrawGridLines(false);      yAxis.setTextColor(Color.WHITE);      yAxis.setTextSize(12);      // 设置y轴数据偏移量      yAxis.setXOffset(30);      yAxis.setYOffset(-3);      yAxis.setAxisMinimum(0);        //Matrix matrix = new Matrix();      // x轴缩放1.5倍      //matrix.postScale(1.5f, 1f);      // 在图表动画显示之前进行缩放      //chart.getViewPortHandler().refresh(matrix, chart, false);      // x轴执行动画      //chart.animateX(2000);      chart.invalidate();      return chart;  }</code></pre>    <h2>设置图表数据</h2>    <p>setChartData方法用来设置图表显示的数据,以及折线的属性。</p>    <pre>  <code class="language-java">/**   * 设置图表数据   *   * @param chart  图表   * @param values 数据   */  public static void setChartData(LineChart chart, List<Entry> values) {      LineDataSet lineDataSet;        if (chart.getData() != null && chart.getData().getDataSetCount() > 0) {          lineDataSet = (LineDataSet) chart.getData().getDataSetByIndex(0);          lineDataSet.setValues(values);          chart.getData().notifyDataChanged();          chart.notifyDataSetChanged();      } else {          lineDataSet = new LineDataSet(values, "");          // 设置曲线颜色          lineDataSet.setColor(Color.parseColor("#FFFFFF"));          // 设置平滑曲线          lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);          // 不显示坐标点的小圆点          lineDataSet.setDrawCircles(false);          // 不显示坐标点的数据          lineDataSet.setDrawValues(false);          // 不显示定位线          lineDataSet.setHighlightEnabled(false);            LineData data = new LineData(lineDataSet);          chart.setData(data);          chart.invalidate();      }  }</code></pre>    <h2>更新图表</h2>    <p>notifyDataSetChanged方法用来更新图表,可以动态的显示x轴标签。</p>    <pre>  <code class="language-java">/**   * 更新图表   *   * @param chart     图表   * @param values    数据   * @param valueType 数据类型   */  public static void notifyDataSetChanged(LineChart chart, List<Entry> values,                                          final int valueType) {      chart.getXAxis().setValueFormatter(new IAxisValueFormatter() {          @Override          public String getFormattedValue(float value, AxisBase axis) {              return xValuesProcess(valueType)[(int) value];          }      });        chart.invalidate();      setChartData(chart, values);  }</code></pre>    <h2>x轴数据处理</h2>    <p>xValuesProcess方法用于处理x轴数据。</p>    <p>x轴可以显示三种类型的数据,分别是今日数据、本周数据、本月数据。</p>    <pre>  <code class="language-java">/**   * x轴数据处理   *   * @param valueType 数据类型   * @return x轴数据   */  private static String[] xValuesProcess(int valueType) {      String[] week = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};        if (valueType == dayValue) { // 今日          String[] dayValues = new String[7];          long currentTime = System.currentTimeMillis();          for (int i = 6; i >= 0; i--) {              dayValues[i] = TimeUtils.dateToString(currentTime, TimeUtils.dateFormat_day);              currentTime -= (3 * 60 * 60 * 1000);          }          return dayValues;        } else if (valueType == weekValue) { // 本周          String[] weekValues = new String[7];          Calendar calendar = Calendar.getInstance();          int currentWeek = calendar.get(Calendar.DAY_OF_WEEK);            for (int i = 6; i >= 0; i--) {              weekValues[i] = week[currentWeek - 1];              if (currentWeek == 1) {                  currentWeek = 7;              } else {                  currentWeek -= 1;              }          }          return weekValues;        } else if (valueType == monthValue) { // 本月          String[] monthValues = new String[7];          long currentTime = System.currentTimeMillis();          for (int i = 6; i >= 0; i--) {              monthValues[i] = TimeUtils.dateToString(currentTime, TimeUtils.dateFormat_month);              currentTime -= (4 * 24 * 60 * 60 * 1000);          }          return monthValues;      }      return new String[]{};  }</code></pre>    <h2>在Activity中使用</h2>    <pre>  <code class="language-java">ChartUtils.initChart(chart);  ChartUtils.notifyDataSetChanged(chart, getData(), ChartUtils.dayValue);</code></pre>    <p>布局文件</p>    <pre>  <code class="language-java"><com.github.mikephil.charting.charts.LineChart          android:id="@+id/chart"          android:layout_width="match_parent"          android:layout_height="match_parent" /></code></pre>    <p> </p>    <p> </p>    <p> </p>