美文网首页Android开发Android技术知识Android开发
Android MPAndroidChart 之自定义Marke

Android MPAndroidChart 之自定义Marke

作者: 壹袁 | 来源:发表于2019-10-31 20:02 被阅读0次

    本文代码:https://github.com/AndroidKid19/MPAndroidChartProject

    MPAndroidChart是一款基于Android的开源图表库,MPAndroidChart不仅可以在Android设备上绘制各种统计图表,而且可以对图表进行拖动和缩放操作,应用起来非常灵活。MPAndroidChart显得更为轻巧和简单,拥有常用的图表类型:线型图、饼图、柱状图和散点图。
    Github 地址:https://github.com/PhilJay/MPAndroidChart

    依赖:

    Project 的build.gradle文件中添加

    allprojects {
        repositories {
            maven { url 'https://jitpack.io' }
        }
    }
    

    然后在 module中的build,gradle 中添加

    implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
    

    不满足可简单粗暴下载下载源码并将MPChartLib引入自己的项目中。

    自定义MarkerView

    1 MarkerView 概念

    Android里面只要用过图表的应该都知道MPAndroidChart这个库。这个库在iOS里面也有对应Charts,所以一般移动端做图表,Android和iOS两端都要实现同样的效果,他们是不错的一个选择。但是,对于图表这种包含的情况非常复杂的东西,很难满足大家各种各样的需求,所以很多都需要自定义。下面就是给大家分享一下自己写的自适应MarkerView。

    图效果图


    20191031195429.png

    这里的逻辑步骤分为:

    1、创建新类继承自MarkerView

    2、inflate layout进去

    3、重写getOffsetForDrawingAtPoint ,分别处理各种边界情况的偏移

    4、重写draw,绘制底色,根据不同的情况,绘制带箭头的对话框

    没啥好说的来干货吧。


    1.搭建MarkView的布局文件layout_markview

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/shape_square"
        android:orientation="vertical">
        <TextView
            android:id="@+id/tv_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white" />
        <TextView
            android:id="@+id/tv_value"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:textColor="@android:color/white" />
    </LinearLayout>
    

    其中背景 fade_blue.xml 是圆角橙色背景

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:tools="http://schemas.android.com/tools"
        xmlns:android="http://schemas.android.com/apk/res/android"
        tools:ignore="ResourceName">
        <gradient
            android:startColor="#58FACD89"
            android:endColor="#58ffffff"
            android:angle="270"
            />
    </shape>
    

    选中点 ic_brightness_curve_point.xml是圆形白底

    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="oval"
        >
        <solid android:color="@color/colorWhite" />
        <stroke
            android:width="2dp"
            android:color="@color/colorPrimary" />
        <size
            android:width="8dp"
            android:height="8dp" />
    </shape>
    

    2.定义常用变量

     private final int DEFAULT_INDICATOR_COLOR = 0xffFF584f;//指示器默认的颜色
        private final int ARROW_HEIGHT = dp2px(10); // 箭头的高度
        private final int ARROW_WIDTH = dp2px(15); // 箭头的宽度
        private final float ARROW_OFFSET = dp2px(2);//箭头偏移量
        private final float BG_CORNER = dp2px(2);//背景圆角
        private Bitmap bitmapForDot;//选中点图片
        private int bitmapWidth;//点宽
        private int bitmapHeight;//点高
    

    3.定义画笔

      //指示器背景画笔
     Paint bgPaint = new Paint();
     bgPaint.setStyle(Paint.Style.FILL);
     bgPaint.setAntiAlias(true);
     bgPaint.setColor(DEFAULT_INDICATOR_COLOR);
     //箭头画笔
     Paint arrowPaint = new Paint();
     arrowPaint.setStyle(Paint.Style.FILL);
     arrowPaint.setAntiAlias(true);
     arrowPaint.setColor(DEFAULT_INDICATOR_COLOR);       
    

    4.动态绘制三角行及view

    注意:绘制的时候大概有四种特殊情况

    markerView超过上边界超过下边界超过左边界超过右边界、以及正常显示

    //画指示器
            Path path = new Path();
            RectF bRectF;
            if (posY < height + ARROW_HEIGHT + bitmapHeight / 2f) {//处理超过上边界
                //移动画布并绘制三角形和背景
                canvas.translate(0, height + ARROW_HEIGHT + bitmapHeight / 2f);
                if (posX > chart.getWidth() - (width/2f)) {//超过右边界
                    canvas.translate( -(width/2 - (chart.getWidth() - posX)), 0);
                    /*************绘制三角形  超过上边界 / 超过右边界**/
                    path.moveTo(width/2 - (chart.getWidth() - posX) - ARROW_OFFSET, -(height + ARROW_HEIGHT + ARROW_OFFSET));
                    path.lineTo(ARROW_WIDTH / 2f, -(height - BG_CORNER));
                    path.lineTo(- ARROW_WIDTH / 2f, -(height - BG_CORNER));
                    path.moveTo(width/2 - (chart.getWidth() - posX) - ARROW_OFFSET, -(height + ARROW_HEIGHT + ARROW_OFFSET));
    
                }else{
                    if (posX > width / 2f) {//在图表中间
                        path.moveTo(0, -(height + ARROW_HEIGHT));
                        path.lineTo(ARROW_WIDTH / 2f, -(height - BG_CORNER));
                        path.lineTo(- ARROW_WIDTH / 2f, -(height - BG_CORNER));
                        path.lineTo(0, -(height + ARROW_HEIGHT));
                    } else {//超过左边界
                        canvas.translate(width/2f - posX, 0);
                        /*************绘制三角形 超过上边界 /  超过左边界**/
                        path.moveTo(-(width/2f - posX) - ARROW_OFFSET, -(height + ARROW_HEIGHT + ARROW_OFFSET));
                        path.lineTo(ARROW_WIDTH / 2f, -(height - BG_CORNER));
                        path.lineTo(- ARROW_WIDTH / 2f, -(height - BG_CORNER));
                        path.moveTo(-(width/2f - posX) - ARROW_OFFSET, -(height + ARROW_HEIGHT  + ARROW_OFFSET));
    
                    }
                }
    
                bRectF=new RectF(-width / 2, -height, width / 2, 0);
                canvas.drawPath(path, arrowPaint);
                canvas.drawRoundRect(bRectF, BG_CORNER, BG_CORNER, bgPaint);
                canvas.translate(-width / 2f, -height);
            } else {//没有超过上边界
                //移动画布并绘制三角形和背景
                canvas.translate(0, -height - ARROW_HEIGHT - bitmapHeight / 2f);
                if (posX < width/2f)  {//超过左边界  平移view
                    canvas.translate( width/2f - posX, 0);
    
                    /*************绘制三角形 超过下边界 /  超过左边界**/
                    path.moveTo(-(width/2f - posX) + ARROW_OFFSET, height + ARROW_HEIGHT + ARROW_OFFSET);
                    path.lineTo(ARROW_WIDTH / 2f, height - BG_CORNER);
                    path.lineTo(- ARROW_WIDTH / 2f, height - BG_CORNER);
                    path.moveTo(-(width/2f - posX) + ARROW_OFFSET, height + ARROW_HEIGHT + ARROW_OFFSET);
                }else{
                    if (posX > chart.getWidth() - (width/2f))  {//超过右边界  绘制三角
                        /*************绘制三角形 超过下边界 /  超过右边界**/
                        canvas.translate( -(width/2 - (chart.getWidth() - posX)), 0);
                        path.moveTo(width/2 - (chart.getWidth() - posX) + ARROW_OFFSET, height + ARROW_HEIGHT + ARROW_OFFSET);
                        path.lineTo(ARROW_WIDTH / 2f, height - BG_CORNER);
                        path.lineTo(- ARROW_WIDTH / 2f, height - BG_CORNER);
                        path.moveTo(width/2 - (chart.getWidth() - posX) + ARROW_OFFSET, height + ARROW_HEIGHT + ARROW_OFFSET);
    
                    }else{
                        path.moveTo(0, height + ARROW_HEIGHT);
                        path.lineTo(ARROW_WIDTH / 2f, height - BG_CORNER);
                        path.lineTo(- ARROW_WIDTH / 2f, height - BG_CORNER);
                        path.moveTo(0, height + ARROW_HEIGHT);
                    }
    
                }
    
                bRectF=new RectF(-width / 2, 0, width / 2, height);
    
                canvas.drawPath(path, arrowPaint);
                canvas.drawRoundRect(bRectF, BG_CORNER, BG_CORNER, bgPaint);
                canvas.translate(-width / 2f, 0);
            }
            draw(canvas);
            canvas.restoreToCount(saveId);
    

    5.自定义MarkerView全套代码

    public class LineChartMarkView extends MarkerView {
        private final int DEFAULT_INDICATOR_COLOR = 0xffFF584f;//指示器默认的颜色
        private final int ARROW_HEIGHT = dp2px(10); // 箭头的高度
        private final int ARROW_WIDTH = dp2px(15); // 箭头的宽度
        private final float ARROW_OFFSET = dp2px(2);//箭头偏移量
        private final float BG_CORNER = dp2px(2);//背景圆角
        private Bitmap bitmapForDot;//选中点图片
        private int bitmapWidth;//点宽
        private int bitmapHeight;//点高
    
        private TextView tvDate;
        private TextView tvValue0;
        private TextView tvValue1;
        private ValueFormatter valueFormatter;
        DecimalFormat df = new DecimalFormat("0.00");
    
        public LineChartMarkView(Context context, ValueFormatter valueFormatter) {
            super(context, R.layout.layout_markview);
            this.valueFormatter = valueFormatter;
            tvDate = findViewById(R.id.tv_date);
            tvValue0 = findViewById(R.id.tv_value0);
            tvValue1 = findViewById(R.id.tv_value1);
            //图片自行替换
            bitmapForDot = getBitmap(context, R.drawable.ic_brightness_curve_point);
            bitmapWidth = bitmapForDot.getWidth();
            bitmapHeight = bitmapForDot.getHeight();
        }
    
    
        private static Bitmap getBitmap(Context context,int vectorDrawableId) {
            Bitmap bitmap=null;
            if (Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){
                Drawable vectorDrawable = context.getDrawable(vectorDrawableId);
                bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
                        vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(bitmap);
                vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                vectorDrawable.draw(canvas);
            }else {
                bitmap = BitmapFactory.decodeResource(context.getResources(), vectorDrawableId);
            }
            return bitmap;
        }
    
        @SuppressLint("SetTextI18n")
        @Override
        public void refreshContent(Entry e, Highlight highlight) {
            Chart chart = getChartView();
            if (chart instanceof LineChart) {
                LineData lineData = ((LineChart) chart).getLineData();
                //获取到图表中的所有曲线
                List<ILineDataSet> dataSetList = lineData.getDataSets();
                for (int i = 0; i < dataSetList.size(); i++) {
                    LineDataSet dataSet = (LineDataSet) dataSetList.get(i);
                    //获取到曲线的所有在Y轴的数据集合,根据当前X轴的位置 来获取对应的Y轴值
                    float y = dataSet.getValues().get((int) e.getX()).getY();
                    if (i == 0) {
                        tvValue0.setText(dataSet.getLabel() + ":" + df.format(y * 100) + "%");
                    }
                    if (i == 1) {
                        tvValue1.setText(dataSet.getLabel() + ":" + df.format(y * 100) + "%");
                    }
                }
                tvDate.setText(valueFormatter.getFormattedValue(e.getX()));
            }
            super.refreshContent(e, highlight);
        }
    
        @Override
        public MPPointF getOffset() {
            return new MPPointF(-(getWidth() / 2), -getHeight());
        }
    
    
    
        @Override
        public void draw(Canvas canvas, float posX, float posY) {
            Chart chart = getChartView();
            if (chart == null) {
                super.draw(canvas, posX, posY);
                return;
            }
    
            //指示器背景画笔
            Paint bgPaint = new Paint();
            bgPaint.setStyle(Paint.Style.FILL);
            bgPaint.setAntiAlias(true);
            bgPaint.setColor(DEFAULT_INDICATOR_COLOR);
            //剪头画笔
            Paint arrowPaint = new Paint();
            arrowPaint.setStyle(Paint.Style.FILL);
            arrowPaint.setAntiAlias(true);
            arrowPaint.setColor(DEFAULT_INDICATOR_COLOR);
    
            float width = getWidth();
            float height = getHeight();
    
            int saveId = canvas.save();
            //移动画布到点并绘制点
            canvas.translate(posX, posY);
            canvas.drawBitmap(bitmapForDot, -bitmapWidth / 2f , -bitmapHeight / 2f ,null);
    
            //画指示器
            Path path = new Path();
            RectF bRectF;
            if (posY < height + ARROW_HEIGHT + bitmapHeight / 2f) {//处理超过上边界
                //移动画布并绘制三角形和背景
                canvas.translate(0, height + ARROW_HEIGHT + bitmapHeight / 2f);
                if (posX > chart.getWidth() - (width/2f)) {//超过右边界
                    canvas.translate( -(width/2 - (chart.getWidth() - posX)), 0);
                    /*************绘制三角形  超过上边界 / 超过右边界**/
                    path.moveTo(width/2 - (chart.getWidth() - posX) - ARROW_OFFSET, -(height + ARROW_HEIGHT + ARROW_OFFSET));
                    path.lineTo(ARROW_WIDTH / 2f, -(height - BG_CORNER));
                    path.lineTo(- ARROW_WIDTH / 2f, -(height - BG_CORNER));
                    path.moveTo(width/2 - (chart.getWidth() - posX) - ARROW_OFFSET, -(height + ARROW_HEIGHT + ARROW_OFFSET));
    
                }else{
                    if (posX > width / 2f) {//在图表中间
                        path.moveTo(0, -(height + ARROW_HEIGHT));
                        path.lineTo(ARROW_WIDTH / 2f, -(height - BG_CORNER));
                        path.lineTo(- ARROW_WIDTH / 2f, -(height - BG_CORNER));
                        path.lineTo(0, -(height + ARROW_HEIGHT));
                    } else {//超过左边界
                        canvas.translate(width/2f - posX, 0);
                        /*************绘制三角形 超过上边界 /  超过左边界**/
                        path.moveTo(-(width/2f - posX) - ARROW_OFFSET, -(height + ARROW_HEIGHT + ARROW_OFFSET));
                        path.lineTo(ARROW_WIDTH / 2f, -(height - BG_CORNER));
                        path.lineTo(- ARROW_WIDTH / 2f, -(height - BG_CORNER));
                        path.moveTo(-(width/2f - posX) - ARROW_OFFSET, -(height + ARROW_HEIGHT  + ARROW_OFFSET));
    
                    }
                }
    
                bRectF=new RectF(-width / 2, -height, width / 2, 0);
                canvas.drawPath(path, arrowPaint);
                canvas.drawRoundRect(bRectF, BG_CORNER, BG_CORNER, bgPaint);
                canvas.translate(-width / 2f, -height);
            } else {//没有超过上边界
                //移动画布并绘制三角形和背景
                canvas.translate(0, -height - ARROW_HEIGHT - bitmapHeight / 2f);
                if (posX < width/2f)  {//超过左边界  平移view
                    canvas.translate( width/2f - posX, 0);
    
                    /*************绘制三角形 超过下边界 /  超过左边界**/
                    path.moveTo(-(width/2f - posX) + ARROW_OFFSET, height + ARROW_HEIGHT + ARROW_OFFSET);
                    path.lineTo(ARROW_WIDTH / 2f, height - BG_CORNER);
                    path.lineTo(- ARROW_WIDTH / 2f, height - BG_CORNER);
                    path.moveTo(-(width/2f - posX) + ARROW_OFFSET, height + ARROW_HEIGHT + ARROW_OFFSET);
                }else{
                    if (posX > chart.getWidth() - (width/2f))  {//超过右边界  绘制三角
                        /*************绘制三角形 超过下边界 /  超过右边界**/
                        canvas.translate( -(width/2 - (chart.getWidth() - posX)), 0);
                        path.moveTo(width/2 - (chart.getWidth() - posX) + ARROW_OFFSET, height + ARROW_HEIGHT + ARROW_OFFSET);
                        path.lineTo(ARROW_WIDTH / 2f, height - BG_CORNER);
                        path.lineTo(- ARROW_WIDTH / 2f, height - BG_CORNER);
                        path.moveTo(width/2 - (chart.getWidth() - posX) + ARROW_OFFSET, height + ARROW_HEIGHT + ARROW_OFFSET);
    
                    }else{
                        path.moveTo(0, height + ARROW_HEIGHT);
                        path.lineTo(ARROW_WIDTH / 2f, height - BG_CORNER);
                        path.lineTo(- ARROW_WIDTH / 2f, height - BG_CORNER);
                        path.moveTo(0, height + ARROW_HEIGHT);
                    }
    
                }
    
                bRectF=new RectF(-width / 2, 0, width / 2, height);
    
                canvas.drawPath(path, arrowPaint);
                canvas.drawRoundRect(bRectF, BG_CORNER, BG_CORNER, bgPaint);
                canvas.translate(-width / 2f, 0);
            }
            draw(canvas);
            canvas.restoreToCount(saveId);
        }
    
        private int dp2px(int dpValues) {
            return (int) TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP, dpValues,
                    getResources().getDisplayMetrics());
        }
    }
    
    
    

    “如果我比别人看得更远些,那是因为我站在巨人的肩膀上”。至于巨人是谁,我也不知道

    相关文章

      网友评论

        本文标题:Android MPAndroidChart 之自定义Marke

        本文链接:https://www.haomeiwen.com/subject/ovztbctx.html