MPAndroidChart的使用

https://github.com/PhilJay/MPAndroidChart

MPAndroidchart是一个很强大的图表第三方库,功能强大,基本可以满足大多数要求,由于在项目使用到了lineChart和BarChart,现在记录下

public class BarChartManager implements OnChartValueSelectedListener {

    private BarChart mChart;
    private Context mContext;
    private XAxis mXAxis;
    private YAxis mLeftAxis;

    public BarChartManager(BarChart chart, Context context) {
        mContext = context;
        mChart = chart;
        initLineChar();
    }

    /**
     * 设置图表的样式
     */
    public void initLineChar() {
        mChart.setDrawBarShadow(false);
        //设置柱状图Value值显示在柱状图上方 true 为显示上方,默认false value值显示在柱状图里面
        mChart.setDrawValueAboveBar(true);
        //设置描述
        mChart.getDescription().setEnabled(false);
        mChart.setTouchEnabled(true);

        MyMarkerView mv = new MyMarkerView(mContext, R.layout.custom_marker_view);
        //        mv.setChartView(mChart); // For bounds control
        mChart.setMarker(mv);

        // scaling can now only be done on x- and y-axis separately
        //按比例
        mChart.setPinchZoom(false);
        //是否能拖动
        mChart.setDragEnabled(false);
        //是否能缩放
        mChart.setScaleEnabled(false);
        //是否绘制网格背景
        mChart.setDrawGridBackground(false);
        mChart.setOnChartValueSelectedListener(this);

        mXAxis = mChart.getXAxis();
        //设置x轴文本显示位置
        mXAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //绘制x轴网格线
        mXAxis.setDrawGridLines(false);
        //缩放的时候有用,比如放大的时候,我不想把横轴的月份再细分
        mXAxis.setGranularity(1f); // only intervals of 1 day
        //强制有多少个刻度
        mXAxis.setLabelCount(7);
        //设置问题的旋转角度
        mXAxis.setLabelRotationAngle(0);
        //        mXAxis.setAxisLineColor(ResUtil.getColor(R.color.color_333));
        //        mXAxis.setTextColor(ResUtil.getColor(R.color.color_333));

        mLeftAxis = mChart.getAxisLeft();
        mLeftAxis.setDrawLabels(true);
        mLeftAxis.setDrawGridLines(true);
        mLeftAxis.setDrawAxisLine(false);
        mLeftAxis.setLabelCount(6, false);
        mLeftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        //        mLeftAxis.setAxisLineColor(ResUtil.getColor(R.color.color_999));
        //        mLeftAxis.setTextColor(ResUtil.getColor(R.color.color_999));
        mLeftAxis.setSpaceTop(15f);
        mLeftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        mLeftAxis.setAxisMaximum(2000f);
        mLeftAxis.setDrawZeroLine(false);

        YAxis rightAxis = mChart.getAxisRight();
        rightAxis.setEnabled(false);
        mChart.getLegend().setEnabled(false);

        mChart.animateXY(2000, 2000);
    }

    public static final int[] MATERIAL_COLORS = {
            rgb("#54D6B0"), rgb("#BED3FE"), rgb("#F0C33B"), rgb("#F8964E")
    };

    /**
     * 设置数据
     *
     * @param count
     * @param range
     */
    public void showBarChart(int count, float range) {
        //模拟数据
        final String[] mDate = new String[4];
        mDate[0] = "凌晨";
        mDate[1] = "6:00";
        mDate[2] = "中午";
        mDate[3] = "18:00";

        Float[] mScore = new Float[4];
        mScore[0] = 1400f;
        mScore[1] = 1000f;
        mScore[2] = 200f;
        mScore[3] = 300f;

        //设置横坐标值
        mXAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if (mDate.length == 0) {
                    return "";
                }
                if (value < 0 || value > mDate.length) {
                    return "";
                }
                return mDate[(int) value % mDate.length];
            }
        });
        //        mLeftAxis.setValueFormatter(new IAxisValueFormatter() {
        //            @Override
        //            public String getFormattedValue(float value, AxisBase axis) {
        //                return null;
        //            }
        //        });

        ArrayList yVals1 = new ArrayList();
        for (int i = 0; i < mScore.length; i++) {
            yVals1.add(new BarEntry(i, mScore[i]));
        }


        BarDataSet set1;
        if (mChart.getData() != null && mChart.getData().getDataSetCount() > 0) {

            set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
            mChart.invalidate();
        } else {

            set1 = new BarDataSet(yVals1, "");
            set1.setDrawIcons(false);
            //设置柱的颜色
            set1.setColors(MATERIAL_COLORS);
            //设置高亮选中透明值
            set1.setHighLightAlpha(50);
            //绘制显示数据
            set1.setDrawValues(true);
            ArrayList dataSets = new ArrayList();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            data.setValueTextSize(mContext.getResources().getDimensionPixelOffset(R.dimen.normal_7sp));
            data.setValueTextColor(ResUtil.getColor(R.color.colorAccent));
            data.setBarWidth(0.5f);

            mChart.setData(data);
            mChart.invalidate();
        }

    }

    protected RectF mOnValueSelectedRectF = new RectF();

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        if (e == null)
            return;

        RectF bounds = mOnValueSelectedRectF;
        mChart.getBarBounds((BarEntry) e, bounds);
        MPPointF position = mChart.getPosition(e, YAxis.AxisDependency.LEFT);

        Log.i("bounds", bounds.toString());
        Log.i("position", position.toString());

        Log.i("x-index",
                "low: " + mChart.getLowestVisibleX() + ", high: " + mChart.getHighestVisibleX());

        MPPointF.recycleInstance(position);
    }

    @Override
    public void onNothingSelected() {

    }


}
public class LineChartManager implements OnChartValueSelectedListener, OnChartGestureListener {

    private LineChart mChart;
    private Context mContext;

    public LineChartManager(LineChart chart, Context context) {
        mContext = context;
        mChart = chart;
        initLineChar();
    }

    /**
     * 设置图标的样式
     */
    public void initLineChar() {
        //手势监听
        mChart.setOnChartGestureListener(this);
        //监听数据单击事件
        mChart.setOnChartValueSelectedListener(this);
        //是否显示网格线
        mChart.setDrawGridBackground(false);

        //是否显示描述
        mChart.getDescription().setEnabled(false);

        // 是否能触摸
        mChart.setTouchEnabled(true);

        //能否拖动
        mChart.setDragEnabled(true);
        //是否缩放
        mChart.setScaleEnabled(true);
        // mChart.setScaleXEnabled(true);
        // mChart.setScaleYEnabled(true);

        // if disabled, scaling can be done on x- and y-axis separately  按比例
        mChart.setPinchZoom(true);

        // set an alternative background color
        //         mChart.setBackgroundColor(Color.GRAY);

        // create a custom MarkerView (extend MarkerView) and specify the layout
        // to use for it
        //提示器
        MyMarkerView mv = new MyMarkerView(mContext, R.layout.custom_marker_view);
        mv.setChartView(mChart); // For bounds control
        mChart.setMarker(mv); // Set the marker to the chart

        // x-axis limit line
        //x轴限制线
        LimitLine llXAxis = new LimitLine(10f, "Index 10");
        llXAxis.setLineWidth(4f);
        llXAxis.enableDashedLine(10f, 10f, 0f);
        llXAxis.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);
        llXAxis.setTextSize(10f);

        XAxis xAxis = mChart.getXAxis();
        //设置网格线和样式
        xAxis.setDrawGridLines(false);
        xAxis.enableGridDashedLine(10f, 10f, 0f);
        //        xAxis.setValueFormatter(new MyCustomXAxisValueFormatter());
        //        xAxis.addLimitLine(llXAxis); // add x-axis limit line

        //        Typeface tf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");

        LimitLine ll1 = new LimitLine(150f, "Upper Limit");
        ll1.setLineWidth(4f);
        ll1.enableDashedLine(10f, 10f, 0f);
        ll1.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
        ll1.setTextSize(10f);
        //        ll1.setTypeface(tf);

        LimitLine ll2 = new LimitLine(-30f, "Lower Limit");
        ll2.setLineWidth(4f);
        ll2.enableDashedLine(10f, 10f, 0f);
        ll2.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);
        ll2.setTextSize(10f);
        //        ll2.setTypeface(tf);

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.removeAllLimitLines(); // reset all limit lines to avoid overlapping lines
        leftAxis.addLimitLine(ll1);
        leftAxis.addLimitLine(ll2);
        leftAxis.setAxisMaximum(200f);
        leftAxis.setAxisMinimum(-50f);
        //leftAxis.setYOffset(20f);
        leftAxis.enableGridDashedLine(10f, 10f, 0f);
        //绘制0度线
        leftAxis.setDrawZeroLine(false);
        //绘制Y轴线
        leftAxis.setDrawAxisLine(false);

        // limit lines are drawn behind data (and not on top)允许控制LimitLines之间的z轴上的实际的数据顺序。如果设置为true,LimitLines在真实数据后边绘制,,
        // 否则在上面。默认false
        leftAxis.setDrawLimitLinesBehindData(true);
        //绘制右边y轴
        mChart.getAxisRight().setEnabled(false);
        //限定可以缩放倍数
        //        mChart.getViewPortHandler().setMaximumScaleY(2f);
        //        mChart.getViewPortHandler().setMaximumScaleX(2f);

        // add data
        //        setData(45, 100);

        //        mChart.setVisibleXRange(20);
        //        mChart.setVisibleYRange(20f, AxisDependency.LEFT);
        //        mChart.centerViewTo(20, 50, AxisDependency.LEFT);

        //动画时间
        mChart.animateX(2500);
        //mChart.invalidate();

        //标注
        Legend l = mChart.getLegend();
        //标注类型
        l.setForm(Legend.LegendForm.CIRCLE);

        // // dont forget to refresh the drawing
        // mChart.invalidate();
    }


    public void showLineChart(int count, float range) {


        //模拟数据
        ArrayList values = new ArrayList();

        for (int i = 0; i < count; i++) {

            float val = (float) (Math.random() * range) + 3;
            //添加数据
            values.add(new Entry(i, val, mContext.getResources().getDrawable(R.drawable.star)));
        }


        LineDataSet set1;

        if (mChart.getData() != null && mChart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0);
            set1.setValues(values);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        } else {
            //标注内容
            set1 = new LineDataSet(values, "DataSet 1");
            //绘制数据点的图标
            set1.setDrawIcons(false);

            //连接虚线
            set1.enableDashedLine(10f, 5f, 0f);
            //            set1.enableDashedHighlightLine(10f, 5f, 0f);
            set1.setColor(Color.BLACK);
            set1.setCircleColor(Color.BLACK);
            set1.setLineWidth(1f);
            set1.setCircleRadius(3f);
            set1.setDrawCircleHole(false);
            set1.setValueTextSize(9f);
            set1.setDrawFilled(true);
            set1.setFormLineWidth(1f);
            set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
            set1.setFormSize(15.f);
            set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);

            if (Utils.getSDKInt() >= 18) {
                //填充颜色
                Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.fade_red);
                set1.setFillDrawable(drawable);
            } else {
                set1.setFillColor(Color.BLACK);
            }

            ArrayList dataSets = new ArrayList();
            dataSets.add(set1); // add the datasets

            // create a data object with the datasets
            LineData data = new LineData(dataSets);

            // set data
            mChart.setData(data);
        }
    }


    @Override
    public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
        Log.i("Gesture", "START, x: " + me.getX() + ", y: " + me.getY());
    }

    @Override
    public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
        Log.i("Gesture", "END, lastGesture: " + lastPerformedGesture);

        // un-highlight values after the gesture is finished and no single-tap
        if (lastPerformedGesture != ChartTouchListener.ChartGesture.SINGLE_TAP)
            mChart.highlightValues(null); // or highlightTouch(null) for callback to onNothingSelected(...)
    }

    @Override
    public void onChartLongPressed(MotionEvent me) {
        Log.i("LongPress", "Chart longpressed.");
    }

    @Override
    public void onChartDoubleTapped(MotionEvent me) {
        Log.i("DoubleTap", "Chart double-tapped.");
    }

    @Override
    public void onChartSingleTapped(MotionEvent me) {
        Log.i("SingleTap", "Chart single-tapped.");
    }

    @Override
    public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {
        Log.i("Fling", "Chart flinged. VeloX: " + velocityX + ", VeloY: " + velocityY);
    }

    @Override
    public void onChartScale(MotionEvent me, float scaleX, float scaleY) {
        Log.i("Scale / Zoom", "ScaleX: " + scaleX + ", ScaleY: " + scaleY);
    }

    @Override
    public void onChartTranslate(MotionEvent me, float dX, float dY) {
        Log.i("Translate / Move", "dX: " + dX + ", dY: " + dY);
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        Log.i("Entry selected", e.toString());
        Log.i("LOWHIGH", "low: " + mChart.getLowestVisibleX() + ", high: " + mChart.getHighestVisibleX());
        Log.i("MIN MAX", "xmin: " + mChart.getXChartMin() + ", xmax: " + mChart.getXChartMax() + ", ymin: " + mChart
                .getYChartMin() + ", ymax: " + mChart.getYChartMax());
    }

    @Override
    public void onNothingSelected() {
        Log.i("Nothing selected", "Nothing selected.");
    }
}

以上只是根据项目需求简单做的例子,具体情况还是要根据自己的需要更新各个参数值。

你可能感兴趣的:(MPAndroidChart的使用)