一.概述
MPAndroidChart是一款基于Android的开源图表库,MPAndroidChart不仅可以在Android设备上绘制各种统计图表,而且可以对图表进行拖动和缩放操作,应用起来非常灵活。MPAndroidChart同样拥有常用的图表类型:线型图、饼图、柱状图和散点图。
GitHub地址:
https://github.com/PhilJay/MPAndroidChart
二.以BarChart为例进行源码讲解
MPAndroidChart中集合了特别多的Chart类型,当然了我们常用的几个图表仅仅只有那么几种对吧,比如说像线性图,就像你高中时候的函数图。比如说饼状图,这个你也应该知道吧,很常见的一种图表。还有一种图表雷达图,知道不?就是这个样子的:
见识过吧,这种图表。然后还有一种就是我们今天让讲解的BarChart,柱状图。
我们先看一下BarChart是怎么在XML里面怎么得到的:
(1)首先我们在我的XML资源文件里添加上BarChart,这个在上一篇博客中也提到了,很简单。
<com.github.mikephil.charting.charts.BarChart
android:id="@+id/chart1"
android:layout_width="match_parent"
android:layout_height="360dp" /></span>
(2)然后我们在View中得到这个对象。
mChart = (BarChart) findViewById(R.id.chart1);
(3)然后我们找到BarChart这个对象的类,我们看看他里面到底有什么呢,之前我们有分析过大体是有什么呢,会不会和我们的猜测差不多呢。
public class BarChart extends BarLineChartBase<BarData> implements BarDataProvider {
/** flag that enables or disables the highlighting arrow */
private boolean mDrawHighlightArrow = false;
/**
* if set to true, all values are drawn above their bars, instead of below their top
*/
private boolean mDrawValueAboveBar = true;
/**
* if set to true, a grey area is drawn behind each bar that indicates the maximum value
*/
private boolean mDrawBarShadow = false;
/**
* if set to true, the width of bar will scale by counts of bars
*/
private boolean mAutoScale = true;
/**
* bar's width without bar space
*/
private float barWidthSize;
/**
* bar first onLayout if first this is true
*/
private boolean isFirstOnLayout = true;
public BarChart(Context context) {
super(context);
}
public BarChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BarChart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
先看代码的第一部分,我们看到了BarChart继承自 BarLineChartBase<BarData>,然后实现了一个BarDataProvider的这个借口,我们在去看一下BarLineChartBase<BarData>这个类里是什么样的吧。
public abstract class BarLineChartBase<T extends BarLineScatterCandleBubbleData<? extends IBarL