文章目录
前言
实验室的项目需要做一个折线图波形,来显示数据。在MATLAB上,只需要一个plot函数就行了,但是在Android上,需要借助一个第三方开源库MPAndroid来实现。本文是对MPAndroidCharts的一个学习和总结。
MPAndroidChart是一款基于Android的开源图表库,它能实现很多常用的图表类型,如:线型图、饼图、柱状图和散点图。除此之外,它还提供了一些对图表的操作功能,如拖拽、缩放、显示动画效果等。基本上,该开源库能够满足一般性图表绘制需求。
开发环境
开发环境主要包括开源库版本、IDE的环境和操作系统,不同环境会有不同的配置和使用方法,很多技术贴不喜欢在文章开头声明自己所用的开发环境,这样会对人产生很大的误导。
- Windows 10 Enterprise 64bit
- Android Studio 3.1.2
- Gradle 4.1
- MPAndroidChart 2.2.5
安装和配置
在project的build.gradle
文件中的buildscript
节点下加入如下代码:
allprojects {
repositories {
maven {
url 'https://jitpack.io' }
}
}
在APP的build.gradle
文件中的dependencies
配置依赖库,我们使用V2.2.5的版本(并不是最新版):
implementation 'com.github.PhilJay:MPAndroidChart:v2.2.5'
配置完之后,点击Sysnc Now
就行了。
一个简单的折线图Demo
布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.github.mikephil.charting.charts.LineChart
android:id="@+id/chart1"
android:layout_width="match_parent"
android:layout_height="300dp"
/>
</RelativeLayout>
Activity文件
package com.example.jason.mpandroidchatrsdemo;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendForm;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.LimitLine.LimitLabelPosition;
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.highlight.Highlight;
import com