最近在做mWork的时候.销售报表是要用到圆饼图的..于是在github上找了一圈开源的第三方图表库.发现了这个--MPAndroidChart
我本人是不太想用之前用过的第三方的图库的..上一个APP 用过 WilliamChart/hellocharts
现在来介绍一下 这个MPAndroidChart MPAndroidChart的效果还是蛮好的,提供各种动画,这个也是我使用MPAndroidChart
Github地址连接,后面是youtube上面演示MPAndroidChart的视频,MPAndroidChart由于提供了动画效果,为了兼容低版本的Android系统,MPAndroidChart需要添加nineoldandroids-2.4.0-2.jar作为依赖库,所以如果项目中使用这个表格库,需要同时导入这个两个jar,当然如果使用libproject的方式,就不用了。
https://github.com/PhilJay/MPAndroidChart
https://www.youtube.com/watch?v=ufaK_Hd6BpI
支持功能
核心功能:
- 支持x,y轴缩放
- 支持拖拽
- 支持手指滑动
- 支持高亮显示
- 支持保存图表到文件中
- 支持从文件(txt)中读取数据
- 预先定义颜色模板
- 自动生成标注
- 支持自定义x,y轴的显示标签
- 支持x,y轴动画
- 支持x,y轴设置最大值和附加信息
- 支持自定义字体,颜色,背景,手势,虚线等
显示的图表类型:
- LineChart (with legend, simple design) (线性图)
-
LineChart (with legend, simple design)(线性图)
-
LineChart (cubic lines)(线性图)
-
LineChart (single DataSet) (线性图)
-
BarChart2D (with legend, simple design)(柱状图)
- BarChart2D (grouped DataSets)(柱状图)
- BarChart2D
- PieChart (with selection, ...)(饼状图)
- ScatterChart (with squares, triangles, circles, ... and more)(散列图)
- CandleStickChart (for financial data)
- RadarChart (spider web chart)(螂蛛网图)
使用方法
1、直接使用jar方式,需要导入mpchartlib.jar,nineoldandroidsjar。
2、使用libproject的方式,作为项目依赖。
步骤:
如果使用 LineChart, BarChart, ScatterChart, CandleStickChart or PieChart
, 可以直接在xml中定义。
<com.github.mikephil.charting.charts.LineChart
android:id="@+id/chart"
android:layout_width="match_parent"
android:layout_height="match_parent" />
LineChart chart = (LineChart) findViewById(R.id.chart);
或则直接在代码中声明和实例化。
LineChart chart = new LineChart(Context);
主要的Api方法:
-
setDescription(String desc)
: 设置表格的描述 -
setDescriptionTypeface(Typeface t)
:自定义表格中显示的字体 -
setDrawYValues(boolean enabled)
: 设置是否显示y轴的值的数据 -
setValuePaintColor(int color)
:设置表格中y轴的值的颜色,但是必须设置setDrawYValues(true) -
setValueTypeface(Typeface t):设置字体
-
setValueFormatter(DecimalFormat format)
: 设置显示的格式 -
setPaint(Paint p, int which)
: 自定义笔刷
-
public ChartData getDataCurrent()
:返回ChartData对象当前显示的图表。它包含了所有信息的显示值最小和最大值等 -
public float getYChartMin()
: 返回当前最小值 -
public float getYChartMax()
: 返回当前最大值 -
public float getAverage()
: 返回所有值的平均值。 -
public float getAverage(int type)
: 返回平均值 -
public PointF getCenter()
: 返回中间点 -
public Paint getPaint(int which)
: 得到笔刷
-
setTouchEnabled(boolean enabled)
: 设置是否可以触摸,如为false,则不能拖动,缩放等 -
setDragScaleEnabled(boolean enabled)
: 设置是否可以拖拽,缩放 -
setOnChartValueSelectedListener(OnChartValueSelectedListener l)
: 设置表格上的点,被点击的时候,的回调函数 -
setHighlightEnabled(boolean enabled)
: 设置点击value的时候,是否高亮显示 -
public void highlightValues(Highlight[] highs)
: 设置高亮显示
-
saveToGallery(String title)
: 保存图表到图库中 -
saveToPath(String title, String pathOnSD)
: 保存. -
setScaleMinima(float x, float y)
: 设置最小的缩放 -
centerViewPort(int xIndex, float val)
: 设置视口 -
fitScreen()
: 适应屏幕
动画:
所有的图表类型都支持下面三种动画,分别是x方向,y方向,xy方向。
-
animateX(int durationMillis)
: x轴方向 -
animateY(int durationMillis)
: y轴方向 -
animateXY(int xDuration, int yDuration)
: xy轴方向
mChart.animateX(3000f); // animate horizontal 3000 milliseconds
// or:
mChart.animateY(3000f); // animate vertical 3000 milliseconds
// or:
mChart.animateXY(3000f, 3000f); // animate horizontal and vertical 3000 milliseconds
注意:如果调用动画方法后,就没有必要调用invalidate()方法,来刷新界面了。
添加数据到图表:
下面是MPAndroidChart中的一个demo实例,简单介绍怎么添加数据到图表中,以及动画显示。package com.xxmassdeveloper.mpchartexample;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendPosition;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.xxmassdeveloper.mpchartexample.notimportant.DemoBase;
import java.util.ArrayList;
public class PieChartActivity extends DemoBase implements OnSeekBarChangeListener,
OnChartValueSelectedListener {
private PieChart mChart;
private SeekBar mSeekBarX, mSeekBarY;
private TextView tvX, tvY;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_piechart);
tvX = (TextView) findViewById(R.id.tvXMax);
tvY = (TextView) findViewById(R.id.tvYMax);
mSeekBarX = (SeekBar) findViewById(R.id.seekBar1);
mSeekBarY = (SeekBar) findViewById(R.id.seekBar2);
mSeekBarX.setProgress(4);
mSeekBarY.setProgress(10);
mChart = (PieChart) findViewById(R.id.chart1);
mChart.setUsePercentValues(true);
mChart.getDescription().setEnabled(false);
mChart.setExtraOffsets(5, 10, 5, 5);
mChart.setDragDecelerationFrictionCoef(0.95f);
mChart.setCenterTextTypeface(mTfLight);
mChart.setCenterText(generateCenterSpannableText());
mChart.setDrawHoleEnabled(true);
mChart.setHoleColor(Color.WHITE);
mChart.setTransparentCircleColor(Color.WHITE);
mChart.setTransparentCircleAlpha(110);
mChart.setHoleRadius(58f);
mChart.setTransparentCircleRadius(61f);
mChart.setDrawCenterText(true);
mChart.setRotationAngle(0);
// enable rotation of the chart by touch
mChart.setRotationEnabled(true);
mChart.setHighlightPerTapEnabled(true);
// mChart.setUnit(" €");
// mChart.setDrawUnitsInChart(true);
// add a selection listener
mChart.setOnChartValueSelectedListener(this);
setData(4, 100);
mChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);
// mChart.spin(2000, 0, 360);
mSeekBarX.setOnSeekBarChangeListener(this);
mSeekBarY.setOnSeekBarChangeListener(this);
Legend l = mChart.getLegend();
l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l.setOrientation(Legend.LegendOrientation.VERTICAL);
l.setDrawInside(false);
l.setXEntrySpace(7f);
l.setYEntrySpace(0f);
l.setYOffset(0f);
// entry label styling
mChart.setEntryLabelColor(Color.WHITE);
mChart.setEntryLabelTypeface(mTfRegular);
mChart.setEntryLabelTextSize(12f);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.pie, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.actionToggleValues: {
for (IDataSet<?> set : mChart.getData().getDataSets())
set.setDrawValues(!set.isDrawValuesEnabled());
mChart.invalidate();
break;
}
case R.id.actionToggleHole: {
if (mChart.isDrawHoleEnabled())
mChart.setDrawHoleEnabled(false);
else
mChart.setDrawHoleEnabled(true);
mChart.invalidate();
break;
}
case R.id.actionDrawCenter: {
if (mChart.isDrawCenterTextEnabled())
mChart.setDrawCenterText(false);
else
mChart.setDrawCenterText(true);
mChart.invalidate();
break;
}
case R.id.actionToggleXVals: {
mChart.setDrawEntryLabels(!mChart.isDrawEntryLabelsEnabled());
mChart.invalidate();
break;
}
case R.id.actionSave: {
// mChart.saveToGallery("title"+System.currentTimeMillis());
mChart.saveToPath("title" + System.currentTimeMillis(), "");
break;
}
case R.id.actionTogglePercent:
mChart.setUsePercentValues(!mChart.isUsePercentValuesEnabled());
mChart.invalidate();
break;
case R.id.animateX: {
mChart.animateX(1400);
break;
}
case R.id.animateY: {
mChart.animateY(1400);
break;
}
case R.id.animateXY: {
mChart.animateXY(1400, 1400);
break;
}
case R.id.actionToggleSpin: {
mChart.spin(1000, mChart.getRotationAngle(), mChart.getRotationAngle() + 360, Easing.EasingOption
.EaseInCubic);
break;
}
}
return true;
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
tvX.setText("" + (mSeekBarX.getProgress()));
tvY.setText("" + (mSeekBarY.getProgress()));
setData(mSeekBarX.getProgress(), mSeekBarY.getProgress());
}
private void setData(int count, float range) {
float mult = range;
ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
// NOTE: The order of the entries when being added to the entries array determines their position around the center of
// the chart.
for (int i = 0; i < count ; i++) {
entries.add(new PieEntry((float) ((Math.random() * mult) + mult / 5), mParties[i % mParties.length]));
}
PieDataSet dataSet = new PieDataSet(entries, "Election Results");
dataSet.setSliceSpace(3f);
dataSet.setSelectionShift(5f);
// add a lot of colors
ArrayList<Integer> colors = new ArrayList<Integer>();
for (int c : ColorTemplate.VORDIPLOM_COLORS)
colors.add(c);
for (int c : ColorTemplate.JOYFUL_COLORS)
colors.add(c);
for (int c : ColorTemplate.COLORFUL_COLORS)
colors.add(c);
for (int c : ColorTemplate.LIBERTY_COLORS)
colors.add(c);
for (int c : ColorTemplate.PASTEL_COLORS)
colors.add(c);
colors.add(ColorTemplate.getHoloBlue());
dataSet.setColors(colors);
//dataSet.setSelectionShift(0f);
PieData data = new PieData(dataSet);
data.setValueFormatter(new PercentFormatter());
data.setValueTextSize(11f);
data.setValueTextColor(Color.WHITE);
data.setValueTypeface(mTfLight);
mChart.setData(data);
// undo all highlights
mChart.highlightValues(null);
mChart.invalidate();
}
private SpannableString generateCenterSpannableText() {
SpannableString s = new SpannableString("MPAndroidChart\ndeveloped by Philipp Jahoda");
s.setSpan(new RelativeSizeSpan(1.7f), 0, 14, 0);
s.setSpan(new StyleSpan(Typeface.NORMAL), 14, s.length() - 15, 0);
s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0);
s.setSpan(new RelativeSizeSpan(.8f), 14, s.length() - 15, 0);
s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - 14, s.length(), 0);
s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - 14, s.length(), 0);
return s;
}
@Override
public void onValueSelected(Entry e, Highlight h) {
if (e == null)
return;
Log.i("VAL SELECTED",
"Value: " + e.getY() + ", index: " + h.getX()
+ ", DataSet index: " + h.getDataSetIndex());
}
@Override
public void onNothingSelected() {
Log.i("PieChart", "nothing selected");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
具体的方法是什么意思...我讲在下面的一个文章中 ,详细解答...
下面 我先提供在GITHUB 我自己下在的JAR包给大家..
这是 GITHUB地址 :https://github.com/PhilJay/MPAndroidChart
这是我下载的 可以直接运行的
http://download.csdn.net/detail/yangbin0513/9713171