本專題講解MPAndroid的使用, 從具體實例出發(fā), 本節(jié)講解庫的基本使用.
參考文獻: 官方文檔
利用本庫來畫圖的流程分三步: 添加依賴, 創(chuàng)建視圖和添加數(shù)據(jù).
一. 添加依賴
- 在項目build.gradle文件下
allprojects {
repositories {
maven { url "https://jitpack.io" }
}
}
- 在模塊build.gradle文件下
dependencies {
implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
}
二. 創(chuàng)建視圖
就跟普通控件一樣使用, 在.xml文件中定義, 在活動中獲取, 比如:
<com.github.mikephil.charting.charts.LineChart
android:id="@+id/chart"
android:layout_width="match_parent"
android:layout_height="match_parent" />
// in this example, a LineChart is initialized from xml
LineChart chart = (LineChart) findViewById(R.id.chart);
三. 添加數(shù)據(jù)
有了控件, 必須有數(shù)據(jù)才能畫圖呀. 這里我們用LineChart來舉例.
我們都知道, 畫二維圖的基本元素是一個點(x, y). 在此框架中, 用Entry類型來封裝X軸和Y軸值, 作為最小數(shù)據(jù)單元. 注意此Entry是框架中的數(shù)據(jù)類型, 不是容器中的Entry.
YourData[] dataObjects = ...;
List<Entry> entries = new ArrayList<Entry>();
for (YourData data : dataObjects) {
// turn your data into Entry objects
entries.add(new Entry(data.getValueX(), data.getValueY()));
}
有了一個List<Entry>
的數(shù)據(jù)源后, 需要將其封裝到一個LineDataSet數(shù)據(jù)類型中. 在這個數(shù)據(jù)類型中做一些畫圖的個性化操作, 比如設(shè)置劃線顏色, 設(shè)置值的字體顏色等等.
LineDataSet dataSet = new LineDataSet(entries, "Label"); // add entries to dataset
dataSet.setColor(...);
dataSet.setValueTextColor(...); // styling, ...
最后的最后, 把設(shè)置完成的DataSet數(shù)據(jù)封裝到一個LineData數(shù)據(jù)類型中. 此數(shù)據(jù)類型才能被畫圖控件識別并加載.
LineData lineData = new LineData(dataSet);
chart.setData(lineData);
chart.invalidate(); // refresh
到此為止, 一張折線圖就畫出來了