日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Android畫圖實(shí)現(xiàn)MPAndroidchart折線圖示例詳解_Android

作者:Activity_ ? 更新時(shí)間: 2022-09-20 編程語言

效果圖

  • 用的是3.1.0的依賴

依賴

    allprojects {
        repositories {
            jcenter()
            maven { url "https://jitpack.io" }
        }
    }
 //依賴
dependencies{
 implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
}

activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <com.github.mikephil.charting.charts.LineChart
        android:id="@+id/lineChart"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff"
        android:layout_margin="15dp"/>
</RelativeLayout>

MainActivity

  private LineChart lineChart;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         lineChart = (LineChart) findViewById(R.id.lineChart);
        //創(chuàng)建描述信息
        Description description = new Description();
        description.setText("測試圖表");
        description.setTextColor(Color.RED);
        description.setTextSize(20);
        lineChart.setDescription(description);//設(shè)置圖表描述信息
        lineChart.setNoDataText("沒有數(shù)據(jù)哦");//沒有數(shù)據(jù)時(shí)顯示的文字
        lineChart.setNoDataTextColor(Color.BLUE);//沒有數(shù)據(jù)時(shí)顯示文字的顏色
        lineChart.setDrawGridBackground(false);//chart 繪圖區(qū)后面的背景矩形將繪制
        lineChart.setDrawBorders(false);//禁止繪制圖表邊框的線
        //lineChart.setBorderColor(); //設(shè)置 chart 邊框線的顏色。
        //lineChart.setBorderWidth(); //設(shè)置 chart 邊界線的寬度,單位 dp。
        //lineChart.setLogEnabled(true);//打印日志
        //lineChart.notifyDataSetChanged();//刷新數(shù)據(jù)
        //lineChart.invalidate();//重繪
        initDate();
        initXY();
    }
private void initDate() {
        /**
         * Entry 坐標(biāo)點(diǎn)對(duì)象  構(gòu)造函數(shù) 第一個(gè)參數(shù)為x點(diǎn)坐標(biāo) 第二個(gè)為y點(diǎn)
         */
        ArrayList<Entry> values1 = new ArrayList<>();
        ArrayList<Entry> values2 = new ArrayList<>();
        values1.add(new Entry(1, 10));
        values1.add(new Entry(2, 15));
        values1.add(new Entry(3, 20));
        values1.add(new Entry(4, 5));
        values1.add(new Entry(5, 30));
        values1.add(new Entry(6, 15));
        values1.add(new Entry(7, 6));
        values2.add(new Entry(1, 20));
        values2.add(new Entry(2, 15));
        values2.add(new Entry(3, 13));
        values2.add(new Entry(4, 8));
        values2.add(new Entry(5, 9));
        values2.add(new Entry(6, 12));
        values2.add(new Entry(7, 15));
        //LineDataSet每一個(gè)對(duì)象就是一條連接線
        LineDataSet set1;
        LineDataSet set2;
//設(shè)置圖例
//獲取圖例
Legend legend=mChart.getLegend();
//是否開啟設(shè)置圖例
legend.setEnabled(true);
//設(shè)置圖例文字大小
legend.setTextSize(50f);
//設(shè)置圖例文字顏色
legend.setTextColor(Color.BLUE);
//如果設(shè)置為true,那么當(dāng)圖例過多或者過長一行顯示不下的時(shí)候就會(huì)自適應(yīng)換行
legend.setWordWrapEnabled(true);
//設(shè)置表格的最大相對(duì)大小,默認(rèn)為0.95f(95%)
legend.setMaxSizePercent(0.95f);
//設(shè)置圖例位置
legend.setPosition(Legend.LegendPosition.ABOVE_CHART_LEFT);
//設(shè)置圖例形狀:如SQUARE、CIRCLE、LINE、DEFAULT
legend.setForm(Legend.LegendForm.CIRCLE);
//設(shè)置圖例XY方向的間隔寬度
legend.setXEntrySpace(20f);
legend.setYEntrySpace(20f);
//設(shè)置圖例標(biāo)簽到文字之間的距離
legend.setFormToTextSpace(20f);
//設(shè)置文本包裝
legend.setWordWrapEnabled(true);
        //判斷圖表中原來是否有數(shù)據(jù)
        if (lineChart.getData() != null && lineChart.getData().getDataSetCount() > 0) {
            //獲取數(shù)據(jù)1
            set1 = (LineDataSet) lineChart.getData().getDataSetByIndex(0);
            set1.setValues(values1);
            set2 = (LineDataSet) lineChart.getData().getDataSetByIndex(1);
            set2.setValues(values2);
            //刷新數(shù)據(jù)
            lineChart.getData().notifyDataChanged();
            lineChart.notifyDataSetChanged();
        } else {
            //設(shè)置數(shù)據(jù)1  參數(shù)1:數(shù)據(jù)源 參數(shù)2:圖例名稱setValueFormatter
            set1 = new LineDataSet(values1, "測試數(shù)據(jù)1");
            set1.setColor(Color.BLUE);//兩個(gè)點(diǎn)之間的距離連接線
            set1.setCircleColor(Color.WHITE);//數(shù)據(jù)展示的圓點(diǎn)顏色
            set1.setLineWidth(3f);//設(shè)置線寬
            set1.setCircleRadius(3f);//設(shè)置焦點(diǎn)圓心的大小
            set1.enableDashedHighlightLine(2f, 5f, 0f);//點(diǎn)擊后的高亮線的顯示樣式
            set1.setHighlightLineWidth(1f);//設(shè)置點(diǎn)擊交點(diǎn)后顯示高亮線寬
            set1.setHighlightEnabled(true);//是否禁用點(diǎn)擊高亮線
            set1.setHighLightColor(Color.YELLOW);//設(shè)置點(diǎn)擊交點(diǎn)后顯示交高亮線的顏色
            set1.setValueTextSize(9f);//設(shè)置顯示值的文字大小
            set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);//直線 變成 曲線
            set1.setDrawValues(false);  //不顯示數(shù)值
//            set1.setValueFormatter(new LargeValueFormatter("℃"));//顯示數(shù)值的樣式
            //陰影填充
//            set1.setDrawFilled(true);//設(shè)置禁用范圍背景填充 陰影
//            set1.setFillDrawable(getResources().getDrawable(R.drawable.line_gradient_bg_shape));
            //設(shè)置數(shù)據(jù)2
            set2 = new LineDataSet(values2, "測試數(shù)據(jù)2");
            set2.setColor(Color.GRAY);//兩個(gè)點(diǎn)之間的距離連接線
            set2.setCircleColor(Color.WHITE);//數(shù)據(jù)展示的圓點(diǎn)顏色
            set2.setLineWidth(3f);//設(shè)置線寬
            set2.setCircleRadius(3f);//設(shè)置焦點(diǎn)圓心的大小
            set2.enableDashedHighlightLine(2f, 5f, 0f);//點(diǎn)擊后的高亮線的顯示樣式
            set2.setHighlightLineWidth(1f);//設(shè)置點(diǎn)擊交點(diǎn)后顯示高亮線寬
            set2.setHighlightEnabled(true);//是否禁用點(diǎn)擊高亮線
            set2.setHighLightColor(Color.YELLOW);//設(shè)置點(diǎn)擊交點(diǎn)后顯示交高亮線的顏色
            set2.setValueTextSize(9f);//設(shè)置顯示值的文字大小
            set2.setMode(LineDataSet.Mode.CUBIC_BEZIER);//直線 變成 曲線
            set2.setDrawValues(false);  //不顯示數(shù)值
            //陰影填充
//            set2.setDrawFilled(true);//設(shè)置禁用范圍背景填充 陰影
//            set2.setFillDrawable(getResources().getDrawable(R.drawable.line_gradient_bg_shape2));
            //保存LineDataSet集合
            ArrayList<ILineDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1); // 添加數(shù)據(jù)集
            dataSets.add(set2);// 添加數(shù)據(jù)集
            //創(chuàng)建LineData對(duì)象 屬于LineChart折線圖的數(shù)據(jù)集合
            LineData data = new LineData(dataSets);
            // 添加到圖表中
            lineChart.setData(data);
            //繪制圖表
            lineChart.invalidate();
        }
    }
   private void initXY() {
        ArrayList<String> xvalue=new ArrayList<>();//x軸時(shí)間
        xvalue.add("10-1");//當(dāng)然這樣可以把X軸的數(shù)據(jù)隨便設(shè)置成啥都行。
        xvalue.add("10-2");
        xvalue.add("10-3");
        xvalue.add("10-4");
        xvalue.add("10-5");
        xvalue.add("10-6");
        xvalue.add("10-7");
        //獲取此圖表的x軸
        XAxis xAxis = lineChart.getXAxis();
        xAxis.setEnabled(true);//設(shè)置軸啟用或禁用 如果禁用以下的設(shè)置全部不生效
        xAxis.setDrawAxisLine(true);//是否繪制軸線
        xAxis.setDrawGridLines(true);//設(shè)置x軸上每個(gè)點(diǎn)對(duì)應(yīng)的線
        xAxis.setDrawLabels(true);//繪制標(biāo)簽  指x軸上的對(duì)應(yīng)數(shù)值
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//設(shè)置x軸的顯示位置
        xAxis.setGranularity(1);//讓x軸上自定義的值和折線上相對(duì)應(yīng)
        xAxis.setAxisLineColor(R.color.white);//設(shè)置橫軸線的顏色
        xAxis.setTextColor(R.color.white);//設(shè)置橫軸字體顏色
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getAxisLabel(float value, AxisBase axis) {
                return xvalue.get((int) value - 1);
            }
        });
//        xAxis.setLabelsToSkip(0);
        //xAxis.setTextSize(20f);//設(shè)置字體
        //xAxis.setTextColor(Color.BLACK);//設(shè)置字體顏色
        //設(shè)置豎線的顯示樣式為虛線
        //lineLength控制虛線段的長度
        //spaceLength控制線之間的空間
//        xAxis.enableGridDashedLine(0f, 0f, 0f);
//        xAxis.setAxisMinimum(0f);//設(shè)置x軸的最小值
//        xAxis.setAxisMaximum(10f);//設(shè)置最大值
//        xAxis.setAvoidFirstLastClipping(true);//圖表將避免第一個(gè)和最后一個(gè)標(biāo)簽條目被減掉在圖表或屏幕的邊緣
//        xAxis.setLabelRotationAngle(0f);//設(shè)置x軸標(biāo)簽的旋轉(zhuǎn)角度
//        設(shè)置x軸顯示標(biāo)簽數(shù)量  還有一個(gè)重載方法第二個(gè)參數(shù)為布爾值強(qiáng)制設(shè)置數(shù)量 如果啟用會(huì)導(dǎo)致繪制點(diǎn)出現(xiàn)偏差
//        xAxis.setLabelCount(10);
//        xAxis.setTextColor(Color.BLUE);//設(shè)置軸標(biāo)簽的顏色
//        xAxis.setTextSize(24f);//設(shè)置軸標(biāo)簽的大小
//        xAxis.setGridLineWidth(10f);//設(shè)置豎線大小
//        xAxis.setGridColor(Color.RED);//設(shè)置豎線顏色
//        xAxis.setAxisLineColor(Color.GREEN);//設(shè)置x軸線顏色
//        xAxis.setAxisLineWidth(5f);//設(shè)置x軸線寬度
//        xAxis.setValueFormatter();//格式化x軸標(biāo)簽顯示字符
        /**
         * Y軸默認(rèn)顯示左右兩個(gè)軸線
         */
        //獲取右邊的軸線
        YAxis rightAxis=lineChart.getAxisRight();
        //設(shè)置圖表右邊的y軸禁用
        rightAxis.setEnabled(false);
        //獲取左邊的軸線
        YAxis leftAxis = lineChart.getAxisLeft();
        //設(shè)置網(wǎng)格線為虛線效果
        leftAxis.enableGridDashedLine(0f, 0f, 0f);
        //是否繪制0所在的網(wǎng)格線
        leftAxis.setDrawZeroLine(false);
        leftAxis.setEnabled(true);//設(shè)置軸啟用或禁用 如果禁用以下的設(shè)置全部不生效
        leftAxis.setDrawAxisLine(true);//是否繪制軸線
        leftAxis.setDrawGridLines(true);//設(shè)置x軸上每個(gè)點(diǎn)對(duì)應(yīng)的線
        leftAxis.setDrawLabels(true);//繪制標(biāo)簽  指x軸上的對(duì)應(yīng)數(shù)值
        leftAxis.setGranularity(1);//讓y軸上自定義的值和折線上相對(duì)應(yīng)
        leftAxis.setAxisLineColor(R.color.white);//設(shè)置縱軸線的顏色
        leftAxis.setTextColor(R.color.white);    //設(shè)置縱軸字體顏色
        lineChart.setTouchEnabled(true); // 設(shè)置是否可以觸摸
        lineChart.setDragEnabled(false); // 是否可以拖拽
        lineChart.setScaleEnabled(false);// 是否可以縮放 x和y軸, 默認(rèn)是true
        lineChart.setScaleXEnabled(false); //是否可以縮放 僅x軸
        lineChart.setScaleYEnabled(false); //是否可以縮放 僅y軸
        lineChart.setPinchZoom(false);  //設(shè)置x軸和y軸能否同時(shí)縮放。默認(rèn)是否
        lineChart.setDoubleTapToZoomEnabled(false);//設(shè)置是否可以通過雙擊屏幕放大圖表。默認(rèn)是true
        lineChart.setHighlightPerDragEnabled(true);//能否拖拽高亮線(數(shù)據(jù)點(diǎn)與坐標(biāo)的提示線),默認(rèn)是true
        lineChart.setDragDecelerationEnabled(false);//拖拽滾動(dòng)時(shí),手放開是否會(huì)持續(xù)滾動(dòng),默認(rèn)是true(false是拖到哪是哪,true拖拽之后還會(huì)有緩沖)
        lineChart.setDragDecelerationFrictionCoef(0.99f);//與上面那個(gè)屬性配合,持續(xù)滾動(dòng)時(shí)的速度快慢,[0,1) 0代表立即停止。
        lineChart.getXAxis().setDrawGridLines(false);//設(shè)置網(wǎng)格線
        lineChart.getAxisLeft().setDrawGridLines(false);//去掉左右邊線
        lineChart.getAxisRight().setDrawGridLines(false);//去掉左右邊線
        final MarkerViews mv = new MarkerViews(this, R.layout.maekertextview,lineChart,xvalue);
        mv.setChartView(lineChart);
        // set the marker to the chart
        lineChart.setMarker(mv);
        //自定義的MarkerView對(duì)象
//        MyMarkerView mv = new MyMarkerView(this, R.layout.item);
//        mv.setChartView(lineChart);
//        lineChart.setMarker(mv);
    }

MyMarkerView 自定義class

public class MarkerViews extends MarkerView {
    private TextView tvContent;//自己定義的xmL
    LineChart lineChart;//圖表控件
    ArrayList<String> xvalue;//X軸數(shù)據(jù)源
    /**
     * Constructor. Sets up the MarkerView with a custom layout resource.
     *
     * @param context
     * @param layoutResource the layout resource to use for the MarkerView
     */
    public MarkerViews(Context context, int layoutResource, LineChart lineChart,ArrayList<String> xvalue) {
        super(context,layoutResource);
        tvContent = (TextView) findViewById(R.id.tvContent1);
        this.lineChart=lineChart;
        this.xvalue=xvalue;
    }
    @Override
    public void refreshContent(Entry e, Highlight highlight) {//重寫refreshContent方法(注意,在  //MPAndroidChart早期版本里這里有三個(gè)參數(shù),這里有兩個(gè),我這是MPAndroidChart 3.0.2版本
        //下面這里是關(guān)鍵的
        LineData lineData=lineChart.getLineData();//得到已經(jīng)繪制成型的折線圖的數(shù)據(jù)
        LineDataSet set=(LineDataSet)lineData.getDataSetByIndex(0);//獲取第一條折線圖Y軸數(shù)據(jù)
        LineDataSet set1=(LineDataSet)lineData.getDataSetByIndex(1);//獲取第二條折線圖Y軸數(shù)據(jù)
        int DataSetIndex=highlight.getDataSetIndex();//獲取點(diǎn)擊的是哪條折線上的交叉點(diǎn),0就是第一條,以此類推
        int index;
        if (DataSetIndex==0){
            index= set.getEntryIndex(e);//根據(jù)點(diǎn)擊的該條折線的點(diǎn),獲取當(dāng)前Y軸數(shù)據(jù)對(duì)應(yīng)的index值,
        }else {
            index= set1.getEntryIndex(e);//根據(jù)點(diǎn)擊的該條折線的點(diǎn),獲取當(dāng)前Y軸數(shù)據(jù)對(duì)應(yīng)的index值,
        }
        //根據(jù)index值,分別獲取當(dāng)前X軸上對(duì)應(yīng)的兩條折線的Y軸的值
        Log.i("x,y軸","/"+xvalue.get(index)+"/"+e.getY());
        tvContent.setText("時(shí)間:"+xvalue.get(index)+"\n在線人數(shù):"+e.getY());
        super.refreshContent(e, highlight);
    }
    @Override
    public MPPointF getOffset() {
        return new MPPointF(-(getWidth() / 2), -getHeight());
    }
}

maekertextview .xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/white"
    >
    <TextView
        android:id="@+id/tvContent1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="7dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:text=""
        android:singleLine="false"
        android:textSize="12dp"
        android:textColor="@android:color/black"
        android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>

常用屬性

  • setDescription(String desc) : 設(shè)置表格的描述
  • setDescriptionTypeface(Typeface t) :自定義表格中顯示的字體
  • setDrawYValues(boolean enabled) : 設(shè)置是否顯示y軸的值的數(shù)據(jù)
  • setValuePaintColor(int color) :設(shè)置表格中y軸的值的顏色,但是必須設(shè)置setDrawYValues(true)
  • setValueTypeface(Typeface t):設(shè)置字體
  • setValueFormatter(DecimalFormat format) : 設(shè)置顯示的格式
  • setPaint(Paint p, int which) : 自定義筆刷
  • public ChartData getDataCurrent() :返回ChartData對(duì)象當(dāng)前顯示的圖表。它包含了所有信息的顯示值最小和最大值等
  • public float getYChartMin() : 返回當(dāng)前最小值
  • public float getYChartMax() : 返回當(dāng)前最大值
  • public float getAverage() : 返回所有值的平均值。
  • public float getAverage(int type) : 返回平均值
  • public PointF getCenter() : 返回中間點(diǎn)
  • public Paint getPaint(int which) : 得到筆刷
  • setTouchEnabled(boolean enabled) : 設(shè)置是否可以觸摸,如為false,則不能拖動(dòng),縮放等
  • setDragScaleEnabled(boolean enabled) : 設(shè)置是否可以拖拽,縮放
  • setOnChartValueSelectedListener(OnChartValueSelectedListener l) : 設(shè)置表格上的點(diǎn),被點(diǎn)擊的時(shí)候,的回調(diào)函數(shù)
  • setHighlightEnabled(boolean enabled) : 設(shè)置點(diǎn)擊value的時(shí)候,是否高亮顯示
  • public void highlightValues(Highlight[] highs) : 設(shè)置高亮顯示
  • saveToGallery(String title) : 保存圖表到圖庫中
  • saveToPath(String title, String pathOnSD) : 保存.
  • setScaleMinima(float x, float y) : 設(shè)置最小的縮放
  • centerViewPort(int xIndex, float val) : 設(shè)置視口
  • fitScreen() : 適應(yīng)屏幕

原文鏈接:https://juejin.cn/post/7124877089425571870

欄目分類
最近更新