MPAndroidChart的简单使用(上)

1,239 阅读3分钟

1. 柱状图BarChart的简单使用

实现的效果:

  1. 自定义X轴Y轴
  2. 设置柱状图的宽度
  3. 分别设置各个柱状图的填充颜色和顶部标签颜色
  4. 极限线

先导入相应的库:

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

布局文件没有用到什么特别的属性值,

<BarChart
        android:id="@+id/report_bc_step"
        ...... />

使用:

特别注意,数据集需要按照X轴的下标顺序排列好,否则点击时会出现某些点无法响应的情况

/**
 *变量的定义
 **/
private lateinit var packingData: ArrayList<BarEntry>    //BarEntry用来存放点的(x,y)值,均为float类型
    private lateinit var valueTextColors: ArrayList<Int>  //顶部标签和柱状图颜色列表
        valueTextColors = arrayListOf()
/**
 *    将要显示的值存进线性列表
 **/
packingData = arrayListOf<BarEntry>()
for (i in 0..11) {
  var value = ...        //获得value值
  val barEntry = BarEntry(i.toFloat(), value)
  barEntry.icon = context!!.getDrawable(R.drawable.ic_star_white)    //设置柱状图的icon
  packingData.add(barEntry)
}

/**
 *    根据柱状图的Y值设置各条柱子填充的颜色值及顶部文字标签的颜色
 **/
for (packing in packingData) {
  if (packing.y >= turnLimite()) valueTextColors.add(context!!.getColor(R.color.colorAccent))
  else if (packing.y >= turnLimite() - subsVaule) valueTextColors.add(
    context!!.getColor(
      R.color.color_FFB046
    )
  )
  else valueTextColors.add(context!!.getColor(R.color.color_F6544F))
}

/**
 * 封装数据
 */
val barDataSet = BarDataSet(packingData, "day")
barDataSet.run {
  this@ReportFragment.yMax = yMax     //获取数据集中Y值的最大值
  setColor(resources.getColor(R.color.colorChart))    //统一设置颜色值为单一色
  valueTypeface =
  ResourcesCompat.getFont(context!!, R.font.montserrat_regular)       //设置图表字体
  setDrawValues(true)     //允许显示标签值
  setDrawIcons(true)      //允许绘制icon,icon设置在BarEntry元素中
  setValueTextColors(valueTextColors)     //为每个柱状图顶部的标签值设置单独的颜色,如果颜色数量小于柱状图数量,柱状图会循环拿取颜色值
  setColors(valueTextColors)      //为每个柱状图设置单独的颜色,同上
  valueTextSize = 12f     //设置标签值大小
  valueFormatter = object : ValueFormatter() {        //标签值格式化
    override fun getFormattedValue(value: Float): String {
      return value.toInt().toString()
    }
  }
  setHighLightColor(resources.getColor(R.color.colorTransparent))        //设置高亮颜色
  highLightAlpha = 255        //设置高亮颜色的透明度为完全不透明
}
val barData = BarData(barDataSet)
context?.let {
  barData.barWidth = 0.5f    //设置柱状图的宽度,默认值为0.8f,可以把值简单理解为百分比
}

/**
 * 将数据设置给图表
 */
report_bc_step.run {
  clear()        //因为该图表是动态跟新的,需要先清除所有绑定的东西
  setData(barData)        //设置数据
  notifyDataSetChanged()    //没有进行图表的刷新,只是更新的数据
  description.isEnabled = false     //不显示描述
  legend.isEnabled = false      //不显示比例图标
  isDoubleTapToZoomEnabled = false      //禁用双击缩放
  isScaleXEnabled = false       //禁用X轴缩放
  isScaleYEnabled = false
  setTouchEnabled(true)        //设置可点击交互
  highlightValue(Highlight(5f, 0, 0), false)        //设置第四个柱状图高亮
  //            else isSetHightLightIndex = false    //不高亮
  //            setPadding(0, 30, 0, 10)
  //            setViewPortOffsets(50f, 0f, 0f, 80f)
  extraTopOffset = 70f        //给MarkerView预留的空间,使图表上方有一块空间是属于MarkerView,柱状图上不去
  extraBottomOffset = 10f        //底部预留10f
  //柱状图的点击事件
  setOnChartValueSelectedListener(object : OnChartValueSelectedListener {
    override fun onNothingSelected() {   }

    override fun onValueSelected(e: Entry?, h: Highlight?) {   }
  })
}

/**
 *    设置X轴
 */
report_bc_step.xAxis.run {
  setDrawGridLines(false)        //不绘制网格线
  setDrawAxisLine(false)        //不绘制X轴线
  position = XAxis.XAxisPosition.BOTTOM        //X轴位置默认在顶部,将其设置在底部
  textSize = 11f        //X轴字体大小
  textColor = resources.getColor(R.color.colorLightContent)    //颜色
  typeface =
  ResourcesCompat.getFont(context!!, R.font.montserrat_regular)
  //设置X轴值
  setLabelCount(4, false)        //设置显示四个标签
  valueFormatter = object : ValueFormatter() {        //标签格式化
    override fun getFormattedValue(value: Float): String {
      var des = ""
      when (value) {
        0f -> des = "00:00"
        3f -> des = "06:00"
        6f -> des = "12:00"
        9f -> des = "18:00"
      }
      return des
    }
  }
}

/**
 * 设置Y轴,Y轴默认左右两边都有显示,先隐藏右边Y轴
 */
report_bc_step.axisRight.run {
  setDrawGridLines(false)
  setDrawAxisLine(false)
  isEnabled = false
}
report_bc_step.axisLeft.run {
  setDrawGridLines(false)
  setDrawAxisLine(false)
  setSpaceMax(50f)
  //            isGranularityEnabled = true     //解决markerView挡住BarView的问题
  //            granularity = 5000f     //直接设置间距,最大值设置大2000f
  resetAxisMinimum()        //重置最小值
  resetAxisMaximum()
  setAxisMinValue(0f)        //设置最小值
  setAxisMaxValue(getMax())        //设置最大值
  setLabelCount(3, true)        //设置标签值
  valueFormatter = object : ValueFormatter() {    //标签格式化
    ......
  }
  //添加极限线
  removeAllLimitLines()        //先移除之前的极限线
  //定义极限线,参数分别为线的Y值和值的格式化
  val ll = LimitLine(limitValue.toFloat(), "${limitValue.toFloat() / 1000f}K")
  ll.lineColor = resources.getColor(R.color.colorAccent)
  ll.textColor = resources.getColor(R.color.colorAccent)
  ll.typeface = ResourcesCompat.getFont(context!!, R.font.montserrat_regular)
  ll.textSize = 12f
  ll.enableDashedLine(8f, 6f, 1f)        //虚线
  ll.labelPosition = LimitLine.LimitLabelPosition.LEFT_TOP    //标签位置
  addLimitLine(ll)
}
//全部设置完毕后重绘制图表,如果没有进行界面的刷新不需要invalidate()
report_bc_step.invalidate()