android 大屏图表 MPAndroidChart 折线图 曲线图 柱状图 圆角柱状图 条形图
圆角柱状图需修改源码:BarChartRenderer.javadrawDataSet方法。如果想要XY轴都有线 设置这两个方法。如果想在上方注释这个。设置XY轴 加个单位。
·
//图表库
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
X轴:XAxis
Y轴:YAxis
图例:Legend
描述:Description
限制线:LimitLine
显示的视图:MarkerView (就是选择中的时候显示的样子)
折线图:
layout
<?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"
android:background="@color/black"
android:orientation="vertical">
<com.github.mikephil.charting.charts.LineChart
android:id="@+id/chart1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
private LineChart charts ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_colored_lines);
charts = findViewById(R.id.chart1);
MpAndroidchart(charts);
}
private void MpAndroidchart(LineChart charts) {
//是否显示边框
charts.setDrawBorders(false);
//得到X轴
XAxis xAxis = charts.getXAxis();
//设置X轴的位置 (不设置默认在上方)
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
//设置X轴坐标之间的最小间隔(因为此图有缩放功能,X轴,Y轴可设置可缩放)
xAxis.setGranularity(1f);
//设置X轴的刻度数量 第二个参数表示是否平均分配
xAxis.setLabelCount(7, true);
//设置X轴的值(最小值、最大值、然后会根据设置的刻度数量自动分配刻度显示)
xAxis.setAxisMinimum(1f);
xAxis.setAxisMaximum(7f);
//X轴文字颜色
xAxis.setTextColor(Color.WHITE);
//X轴网格线颜色
xAxis.setGridColor(Color.TRANSPARENT);
//X轴颜色
xAxis.setAxisLineColor(Color.WHITE);
//设置X轴文字显示
xAxis.setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return (int)value+"月";
}
})
//设置X轴动画
// charts.animateX(3000);
//得到Y轴
YAxis leftYAxis = charts.getAxisLeft();
YAxis rightYAxis =charts.getAxisRight();
//设置从左侧Y轴值
leftYAxis.setAxisMinimum(0f);
leftYAxis.setAxisMaximum(100f);
//设置从左侧Y轴值
// rightYAxis.setAxisMinimum(0f);
// rightYAxis.setAxisMaximum(100f);
//右侧Y轴不显示
rightYAxis.setEnabled(false);
//设置Y轴坐标之间的最小间隔(因为此图有缩放功能,X轴,Y轴可设置可缩放)
leftYAxis.setGranularity(1f);
//设置Y轴的刻度数量 第二个参数表示是否平均分配
leftYAxis.setLabelCount(10, true);
//Y轴文字颜色
leftYAxis.setTextColor(Color.WHITE);
//Y轴网格线颜色
leftYAxis.setGridColor(Color.argb(100,255,255,255));
//Y轴颜色
leftYAxis.setAxisLineColor(Color.WHITE);
//设置X轴动画
// charts.animateY(3000);
// //得到限制线
// LimitLine limitLine = new LimitLine(95,"高限制性");
// //宽度
// limitLine.setLineWidth(4f);
// //字体大小
// limitLine.setTextSize(10f);
// //字体颜色
// limitLine.setTextColor(Color.RED);
// //线大小
// limitLine.setLineColor(Color.BLUE);
// //Y轴添加限制线
// leftYAxis.addLimitLine(limitLine);
// //X轴添加限制线
// xAxis.addLimitLine(limitLine);
//得到Legend (下边的颜色线)
Legend legend = charts.getLegend();
//设置Legend 文本颜色
legend.setTextColor(Color.WHITE);
//设置Legend 在顶部显示
legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
//设置Legend 在右侧显示
legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
//设置Legend 在横向显示
legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
//设置标签是否换行(当多条标签时 需要换行显示)
//true:可换行。false:不换行
legend.setWordWrapEnabled(false);
//是否显示Lengend
//true:显示。false:不显示
legend.setEnabled(true);
//得到描述
Description description = new Description();
//是否显示描述
//true:显示。false:不显示
description.setEnabled(true);
//设置x轴描述
description.setText("单位:命中次数");
description.setTextColor(Color.WHITE);
charts.setDescription(description);
//设置XY轴动画
charts.animateXY(3000, 3000);
//设置数据
List<Entry> entries = new ArrayList<>();
for (int i = 0; i < 24; i++) {
entries.add(new Entry(i, (float) (Math.random()) * 80));
}
//一个LineDataSet就是一条线
LineDataSet lineDataSet = new LineDataSet(entries, "温度");
//设置value的字体颜色
lineDataSet.setValueTextColor(Color.WHITE);
//设置曲线值的圆点是实心还是空心
lineDataSet.setDrawCircleHole(false);
//设置显示值的字体大小
lineDataSet.setValueTextSize(9f);
//线模式为圆滑曲线(默认折线)
// lineDataSet.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
//设置折线颜色
lineDataSet.setColor(Color.WHITE);
//设置小圆点颜色
lineDataSet.setCircleColor(Color.WHITE);
//设置填充颜色
lineDataSet.setDrawFilled(true);
lineDataSet.setFillColor(R.color.xian);
// 设置拖拽、缩放等
charts.setDragEnabled(false);
charts.setScaleEnabled(false);
charts.setScaleXEnabled(false);
charts.setScaleYEnabled(false);
// 设置双指缩放
charts.setPinchZoom(true);
LineData data = new LineData(lineDataSet);
charts.setData(data);
}
如果想在上方注释这个。
//设置X轴的位置 (不设置默认在上方)
// xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
如果想要XY轴都有线 设置这两个方法。
//X轴网格线颜色
xAxis.setGridColor(Color.TRANSPARENT);
//Y轴网格线颜色
leftYAxis.setGridColor(Color.argb(100,255,255,255));
线模式为圆滑曲线
//线模式为圆滑曲线(默认折线)
lineDataSet.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
如果不想要填充颜色 :
//设置填充颜色
lineDataSet.setDrawFilled(true);
lineDataSet.setFillColor(R.color.xian);
设置XY轴 加个单位。
//设置X轴文字显示
xAxis.setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return (int)value+"月";
}
});
圆角柱状图
圆角柱状图需修改源码:BarChartRenderer.java drawDataSet方法
if (isCustomFill) {
dataSet.getFill(pos)
.fillRect(
c, mRenderPaint,
buffer.buffer[j],
buffer.buffer[j + 1],
buffer.buffer[j + 2],
buffer.buffer[j + 3],
isInverted ? Fill.Direction.DOWN : Fill.Direction.UP);
}
else {
//这里注释,使用下面的 圆角。
// c.drawRect(buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2],
// buffer.buffer[j + 3], mRenderPaint);
RectF rectF=new RectF(buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2],buffer.buffer[j + 3]);
c.drawRoundRect(rectF,(float)50,(float)50,mRenderPaint);
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="@color/black"
android:layout_height="match_parent">
<com.github.mikephil.charting.charts.BarChart
android:id="@+id/chart1"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
package com.xxmassdeveloper.mpchartexample;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.renderer.scatter.CircleShapeRenderer;
import com.github.mikephil.charting.utils.Fill;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.sbas.xueliapplication.R;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
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.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendForm;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.XAxis.XAxisPosition;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.components.YAxis.AxisDependency;
import com.github.mikephil.charting.components.YAxis.YAxisLabelPosition;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.MPPointF;
import com.xxmassdeveloper.mpchartexample.custom.DayAxisValueFormatter;
import com.xxmassdeveloper.mpchartexample.custom.MyAxisValueFormatter;
import com.xxmassdeveloper.mpchartexample.custom.XYMarkerView;
import com.xxmassdeveloper.mpchartexample.notimportant.DemoBase;
import java.util.ArrayList;
import java.util.List;
import static com.github.mikephil.charting.components.Legend.LegendForm.CIRCLE;
public class BarChartActivity extends DemoBase implements OnSeekBarChangeListener,
OnChartValueSelectedListener {
private BarChart chart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_barchart);
setTitle("BarChartActivity");
chart = findViewById(R.id.chart1);
BarChart(chart);
}
ArrayList<BarEntry> barEntries = new ArrayList<>();
public void BarChart(BarChart barChart){
for (int i = 0; i < 7; i++) {
int val = (int) (Math.random() * (30 + 1));
barEntries.add(new BarEntry(i+1, val));
}
//是否显示边框
barChart.setDrawBorders(false);
//得到X轴
XAxis xAxis = barChart.getXAxis();
//设置X轴的位置 (不设置默认在上方)
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
//设置X轴坐标之间的最小间隔(因为此图有缩放功能,X轴,Y轴可设置可缩放)
xAxis.setGranularity(1);
//设置X轴的刻度数量 第二个参数表示是否平均分配
xAxis.setLabelCount(12, false);
//设置X轴的值(最小值、最大值、然后会根据设置的刻度数量自动分配刻度显示)
xAxis.setAxisMinimum(0);
xAxis.setAxisMaximum(12);
//设置X轴文字显示
xAxis.setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return (int)value+"月";
}
});
//X轴文字颜色
xAxis.setTextColor(Color.WHITE);
//X轴网格线颜色
xAxis.setGridColor(Color.TRANSPARENT);
//X轴颜色
xAxis.setAxisLineColor(Color.WHITE);
//设置X轴动画
// mBinding.lineChart.animateX(3000);
//得到Y轴
YAxis leftYAxis = barChart.getAxisLeft();
YAxis rightYAxis = barChart.getAxisRight();
//设置从左侧Y轴值
leftYAxis.setAxisMinimum(0);
leftYAxis.setAxisMaximum(31);
//设置从左侧Y轴值
// rightYAxis.setAxisMinimum(0f);
// rightYAxis.setAxisMaximum(100f);
//右侧Y轴不显示
rightYAxis.setEnabled(false);
//设置Y轴坐标之间的最小间隔(因为此图有缩放功能,X轴,Y轴可设置可缩放)
leftYAxis.setGranularity(1);
//设置Y轴的刻度数量 第二个参数表示是否平均分配
leftYAxis.setLabelCount(6, true);
//Y轴文字颜色
leftYAxis.setTextColor(Color.WHITE);
//Y轴网格线颜色
leftYAxis.setGridColor(Color.argb(100,14,106,136));
//Y轴颜色
leftYAxis.setAxisLineColor(Color.WHITE);
//设置X轴动画
// mBinding.lineChart.animateY(3000);
// //得到限制线
// LimitLine limitLine = new LimitLine(95,"高限制性");
// //宽度
// limitLine.setLineWidth(4f);
// //字体大小
// limitLine.setTextSize(10f);
// //字体颜色
// limitLine.setTextColor(Color.RED);
// //线大小
// limitLine.setLineColor(Color.BLUE);
// //Y轴添加限制线
// leftYAxis.addLimitLine(limitLine);
// //X轴添加限制线
// xAxis.addLimitLine(limitLine);
//得到Legend (下边的颜色线)
Legend legend = barChart.getLegend();
//设置Legend 文本颜色
legend.setTextColor(Color.WHITE);
//设置Legend 在顶部显示
legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
//设置Legend 在右侧显示
legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
//设置Legend 在横向显示
legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
//设置标签是否换行(当多条标签时 需要换行显示)
//true:可换行。false:不换行
legend.setWordWrapEnabled(false);
//是否显示Lengend
//true:显示。false:不显示
legend.setEnabled(true);
//得到描述
Description description = new Description();
//是否显示描述
//true:显示。false:不显示
description.setEnabled(true);
//设置x轴描述
description.setText("单位:天数");
description.setTextColor(Color.WHITE);
barChart.setDescription(description);
//设置XY轴动画
barChart.animateXY(3000, 3000);
//一个LineDataSet就是一条线
BarDataSet barDataSet = new BarDataSet(barEntries, "");
//设置value的字体颜色
barDataSet.setValueTextColor(Color.argb(100,14,106,136));
barDataSet.setValueFormatter(new IValueFormatter() {
@Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
return (int)value+"";
}
});
List<Fill> gradientFills = new ArrayList<>();
int startColor1 = ContextCompat.getColor(this, android.R.color.holo_orange_light);
int endColor1 = ContextCompat.getColor(this, android.R.color.holo_blue_dark);
gradientFills.add(new Fill(startColor1, endColor1));
// barDataSet.setFills(gradientFills);
//设置曲线值的圆点是实心还是空心
// barDataSet.setDrawCircleHole(false);
//设置显示值的字体大小
barDataSet.setValueTextSize(10f);
//设置折线颜色
barDataSet.setColor(Color.argb(100,14,106,136));
// 设置拖拽、缩放等
barChart.setDragEnabled(false);
barChart.setScaleEnabled(false);
barChart.setScaleXEnabled(false);
barChart.setScaleYEnabled(false);
// 设置双指缩放
barChart.setPinchZoom(false);
BarData data = new BarData(barDataSet);
barChart.setData(data);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.bar, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.viewGithub: {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("https://github.com/PhilJay/MPAndroidChart/blob/master/MPChartExample/src/com/xxmassdeveloper/mpchartexample/BarChartActivity.java"));
startActivity(i);
break;
}
case R.id.actionToggleValues: {
for (IDataSet set : chart.getData().getDataSets())
set.setDrawValues(!set.isDrawValuesEnabled());
chart.invalidate();
break;
}
case R.id.actionToggleIcons: {
for (IDataSet set : chart.getData().getDataSets())
set.setDrawIcons(!set.isDrawIconsEnabled());
chart.invalidate();
break;
}
case R.id.actionToggleHighlight: {
if (chart.getData() != null) {
chart.getData().setHighlightEnabled(!chart.getData().isHighlightEnabled());
chart.invalidate();
}
break;
}
case R.id.actionTogglePinch: {
if (chart.isPinchZoomEnabled())
chart.setPinchZoom(false);
else
chart.setPinchZoom(true);
chart.invalidate();
break;
}
case R.id.actionToggleAutoScaleMinMax: {
chart.setAutoScaleMinMaxEnabled(!chart.isAutoScaleMinMaxEnabled());
chart.notifyDataSetChanged();
break;
}
case R.id.actionToggleBarBorders: {
for (IBarDataSet set : chart.getData().getDataSets())
((BarDataSet) set).setBarBorderWidth(set.getBarBorderWidth() == 1.f ? 0.f : 1.f);
chart.invalidate();
break;
}
case R.id.animateX: {
chart.animateX(2000);
break;
}
case R.id.animateY: {
chart.animateY(2000);
break;
}
case R.id.animateXY: {
chart.animateXY(2000, 2000);
break;
}
case R.id.actionSave: {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
saveToGallery();
} else {
requestStoragePermission(chart);
}
break;
}
}
return true;
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
chart.invalidate();
}
@Override
protected void saveToGallery() {
saveToGallery(chart, "BarChartActivity");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
private final RectF onValueSelectedRectF = new RectF();
@Override
public void onValueSelected(Entry e, Highlight h) {
if (e == null)
return;
RectF bounds = onValueSelectedRectF;
chart.getBarBounds((BarEntry) e, bounds);
MPPointF position = chart.getPosition(e, AxisDependency.LEFT);
Log.i("bounds", bounds.toString());
Log.i("position", position.toString());
Log.i("x-index",
"low: " + chart.getLowestVisibleX() + ", high: "
+ chart.getHighestVisibleX());
MPPointF.recycleInstance(position);
}
@Override
public void onNothingSelected() { }
}
package com.xxmassdeveloper.mpchartexample.notimportant;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.view.View;
import android.widget.Toast;
import com.github.mikephil.charting.charts.Chart;
import com.sbas.xueliapplication.R;
/**
* Base class of all Activities of the Demo Application.
*
* @author Philipp Jahoda
*/
public abstract class DemoBase extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
protected final String[] months = new String[] {
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"
};
protected final String[] parties = new String[] {
"Party A", "Party B", "Party C", "Party D", "Party E", "Party F", "Party G", "Party H",
"Party I", "Party J", "Party K", "Party L", "Party M", "Party N", "Party O", "Party P",
"Party Q", "Party R", "Party S", "Party T", "Party U", "Party V", "Party W", "Party X",
"Party Y", "Party Z"
};
private static final int PERMISSION_STORAGE = 0;
protected Typeface tfRegular;
protected Typeface tfLight;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tfRegular = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");
tfLight = Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf");
}
protected float getRandom(float range, float start) {
return (float) (Math.random() * range) + start;
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.move_left_in_activity, R.anim.move_right_out_activity);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSION_STORAGE) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
saveToGallery();
} else {
Toast.makeText(getApplicationContext(), "Saving FAILED!", Toast.LENGTH_SHORT)
.show();
}
}
}
protected void requestStoragePermission(View view) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Snackbar.make(view, "Write permission is required to save image to gallery", Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
@Override
public void onClick(View v) {
ActivityCompat.requestPermissions(DemoBase.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_STORAGE);
}
}).show();
} else {
Toast.makeText(getApplicationContext(), "Permission Required!", Toast.LENGTH_SHORT)
.show();
ActivityCompat.requestPermissions(DemoBase.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_STORAGE);
}
}
protected void saveToGallery(Chart chart, String name) {
if (chart.saveToGallery(name + "_" + System.currentTimeMillis(), 70))
Toast.makeText(getApplicationContext(), "Saving SUCCESSFUL!",
Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "Saving FAILED!", Toast.LENGTH_SHORT)
.show();
}
protected abstract void saveToGallery();
}
柱状图:
源码不动:
if (isCustomFill) {
dataSet.getFill(pos)
.fillRect(
c, mRenderPaint,
buffer.buffer[j],
buffer.buffer[j + 1],
buffer.buffer[j + 2],
buffer.buffer[j + 3],
isInverted ? Fill.Direction.DOWN : Fill.Direction.UP);
}
else {
//这里注释,使用下面的 圆角。
c.drawRect(buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2],
buffer.buffer[j + 3], mRenderPaint);
// RectF rectF=new RectF(buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2],buffer.buffer[j + 3]);
// c.drawRoundRect(rectF,(float)50,(float)50,mRenderPaint);
}
更多推荐
已为社区贡献18条内容
所有评论(0)