美文网首页
自定义折线图

自定义折线图

作者: Db_z | 来源:发表于2020-03-18 17:12 被阅读0次

    今天来撸一个折线图,斜体文本给我整的直难受,当初找了半天就是没有正常能用的, 后来费了半天劲才整明白,哎,画布真是有点搞不懂,不多说,先上图;

    image.png image.png

    先来初始化一下

       /**
         * 初始化画笔
         */
        private void initPaint() {
            xyPaint = new Paint();
            xyPaint.setAntiAlias(true);
            xyPaint.setStrokeWidth(mXYLineWidth);
            xyPaint.setStrokeCap(Paint.Cap.ROUND);
            xyPaint.setColor(mXYLineColor);
    
            xyTextPaint = new Paint();
            xyTextPaint.setAntiAlias(true);
            xyTextPaint.setTextSize(mXyTextSize);
            xyTextPaint.setStrokeCap(Paint.Cap.ROUND);
            xyTextPaint.setColor(mXyTextColor);
            xyTextPaint.setStyle(Paint.Style.STROKE);
    
            mLinePaint = new Paint();
            mLinePaint.setAntiAlias(true);
            mLinePaint.setStrokeWidth(mXYLineWidth);
            mLinePaint.setStrokeCap(Paint.Cap.ROUND);
            mLinePaint.setColor(mLinecolor);
            mLinePaint.setStyle(Paint.Style.STROKE);
    
            showPaint = new Paint();
            showPaint.setAntiAlias(true);
            showPaint.setStrokeWidth(mXYLineWidth);
            showPaint.setStrokeCap(Paint.Cap.ROUND);
            showPaint.setColor(Color.parseColor("#6f6f6f"));
            showPaint.setStyle(Paint.Style.FILL);
            showPaint.setTextSize(mXyTextSize);
        }
    
        /**
         * 初始化自定义属性
         */
        private void initView(Context context, AttributeSet attrs) {
            TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.brokenLineView);
            mXYLineColor = array.getColor(R.styleable.brokenLineView_dbz_xy_line_color, mXYLineColor);
            mXYLineWidth = (int) array.getDimension(R.styleable.brokenLineView_dbz_xy_line_width, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, mXYLineWidth, getResources().getDisplayMetrics()));
            mXyTextColor = array.getColor(R.styleable.brokenLineView_dbz_xy_text_color, mXyTextColor);
            mXyTextSize = (int) array.getDimension(R.styleable.brokenLineView_dbz_xy_text_size, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, mXyTextSize, getResources().getDisplayMetrics()));
            mLinecolor = array.getColor(R.styleable.brokenLineView_dbz_line_color, mLinecolor);
            mContentColor = array.getColor(R.styleable.brokenLineView_dbz_content_color, mContentColor);
            bgcolor = array.getColor(R.styleable.brokenLineView_dbz_bg_color, bgcolor);
            interval = (int) array.getDimension(R.styleable.brokenLineView_dbz_interval, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, interval, getResources().getDisplayMetrics()));
            array.recycle();
        }
    

    初始化一下画笔和自定义的属性 属性文件在文章尾部

    测量onLayout()

    @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            if (changed) {
                //得到宽度高度
                width = getWidth();
                height = getHeight();
                int dp2 = dpToPx(2);
                int dp3 = dpToPx(3);
                xOrigin = mXYLineWidth;//dp2是y轴文本距离左边,以及距离y轴的距离
                // 测量X轴月份的高度
                xValueRect = getTextBounds("00月00日", xyTextPaint);
                xTextHeight = xValueRect.width(); // 因为是垂直显示所以宽度就是高度
                // 把宽度分成10 左右各占一个间距  总宽度 - 左右距离和中间的距离 除以10列
                interval = (width - ((width / 10) - getPaddingLeft() - getPaddingRight())) / 10;
                // 要把底部文本的高度留出来
                yOrigin = (height - dp2 - xValueRect.height() - dp3 - mXYLineWidth) - xTextHeight;//dp3是x轴文本距离底边,dp2是x轴文本距离x轴的距离
                xInit = interval + xOrigin;
            }
            super.onLayout(changed, left, top, right, bottom);
        }
    

    我的需求就是10天的数据量, 所以我就直接按照10的比例来分类的(如果有需求可以自行修改)
    接下来

    @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawColor(bgcolor);
            drawXY(canvas);
            drawBrokenLineAndPoint(canvas);
        }
    
     /**
         * 绘制XY坐标
         *
         * @param canvas
         */
        private void drawXY(Canvas canvas) {
            //绘制Y轴线
    //        canvas.drawLine(xOrigin - xylinewidth / 2, 0, xOrigin - xylinewidth / 2, yOrigin, xyPaint);
    //        //绘制y轴箭头
    //        xyPaint.setStyle(Paint.Style.STROKE);
    //        Path path = new Path();
    //        path.moveTo(xOrigin - xylinewidth / 2 - dpToPx(5), dpToPx(12));
    //        path.lineTo(xOrigin - xylinewidth / 2, xylinewidth / 2);
    //        path.lineTo(xOrigin - xylinewidth / 2 + dpToPx(5), dpToPx(12));
    //        canvas.drawPath(path, xyPaint);
            //绘制y轴刻度
    //        int yLength = (int) (yOrigin * (1 - 0.1f) / (yValues.size() - 1));//y轴上面空出10%,计算出y轴刻度间距
    //        for (int i = 0; i < yValues.size(); i++) {
    //            //绘制Y轴刻度
    //            canvas.drawLine(xOrigin, yOrigin - yLength * i + xylinewidth / 2, xOrigin, yOrigin - yLength * i + xylinewidth / 2, xyPaint);
    //            xyTextPaint.setColor(xytextcolor);
    //            //绘制Y轴文本
    //            String text = yValues.get(i).value;
    //            Rect rect = getTextBounds(text, xyTextPaint);
    //            canvas.drawText(text, 0, text.length(), xOrigin - xylinewidth - dpToPx(2) - rect.width(), yOrigin - yLength * i + rect.height() / 2, xyTextPaint);
    //        }
    
            //绘制X轴坐标
            canvas.drawLine(xOrigin, yOrigin + mXYLineWidth / 2, width, yOrigin + mXYLineWidth / 2, xyPaint);
    
            //绘制x轴箭头
    //        xyPaint.setStyle(Paint.Style.STROKE);
    //        path = new Path();
            //整个X轴的长度
    //        float xLength = xInit + interval * (xValues.size() - 1) + (width - xOrigin) * 0.1f;
    //        if (xLength < width)
    //        if (xLength > width)
    //            xLength = width;
    //        path.moveTo(xLength - dpToPx(12), yOrigin + xylinewidth / 2 - dpToPx(5));
    //        path.lineTo(xLength - xylinewidth / 2, yOrigin + xylinewidth / 2);
    //        path.lineTo(xLength - dpToPx(12), yOrigin + xylinewidth / 2 + dpToPx(5));
    //        path.moveTo(xLength, yOrigin + xylinewidth / 2);
    //        path.lineTo(xLength, yOrigin + xylinewidth / 2);
    //        path.lineTo(xLength, yOrigin + xylinewidth / 2);
    //        canvas.drawPath(path, xyPaint);
            //绘制x轴刻度
            for (int i = 0; i < xValues.size(); i++) {
                float x = xInit + interval * i;
                if (x >= xOrigin) {//只绘制从原点开始的区域
                    xyTextPaint.setColor(mXyTextColor);
                    canvas.drawLine(x, yOrigin, x, yOrigin, xyPaint);
                    // 如果是选中的 绘制垂直线
                    if (i == selectIndex - 1) {
                        canvas.drawLine(x, yOrigin, x, (float) xValues.get(i).num, xyPaint);
                    }
                    //绘制X轴文本
                    String text = xValues.get(i).value;
                    Rect rect = getTextBounds(text, xyTextPaint);
                    //绘制x轴选中文字和框
                    xyTextPaint.setStyle(Paint.Style.FILL);
    
                    float xV = x - rect.width() / 2;
                    float yV = yOrigin + mXYLineWidth + dpToPx(2) + rect.height();
                    // 画布旋转80度
                    canvas.rotate(-80, xV, yV);
                    canvas.drawText(text, xV - (xTextHeight - xTextHeight / 3), yV + (xTextHeight - xTextHeight / 2), xyTextPaint);
                    canvas.rotate(80, xV, yV);
                    // 水平方向显示的 xy 轴
    //                    canvas.drawText(text, 0, text.length(), xV, yV, xyTextPaint);
    //                } else {
    //                    canvas.drawText(text, 0, text.length(), x - rect.width() / 2, yOrigin + xylinewidth + dpToPx(2) + rect.height(), xyTextPaint);
    //                }
                }
            }
        }
    

    刻画XY轴, 当初画Y轴就是为了给自己找到一个标准,目前项目不需要, 如果需要的可以放开代码

    /**
         * 绘制折线和折线点
         */
        private void drawBrokenLineAndPoint(Canvas canvas) {
            if (xValues.size() <= 0)
                return;
            //设置显示折线的图层
            int layer = canvas.saveLayer(0, 0, width, height, null, Canvas.ALL_SAVE_FLAG);
            drawBrokenLine(canvas);
            drawBrokenPoint(canvas);
            // 将折线超出x轴坐标的部分截取掉
            mLinePaint.setStyle(Paint.Style.FILL);
            mLinePaint.setColor(bgcolor);
            mLinePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
            RectF rectF = new RectF(0, 0, xOrigin, height);
            canvas.drawRect(rectF, mLinePaint);
            mLinePaint.setXfermode(null);
            //保存图层
            canvas.restoreToCount(layer);
        }
    
        /**
         * 绘制折线对应的点位圆圈
         */
        private void drawBrokenPoint(Canvas canvas) {
            float dp3 = dpToPx(3);
            float dp5 = dpToPx(5);
            //绘制节点对应的原点
            for (int i = 0; i < xValues.size(); i++) {
                float x = xInit + interval * i;
                float y = (float) (yOrigin - yOrigin * (1 - 0.1f) * lineValues.get(i).num / yValues.get(yValues.size() - 1).num);
                //绘制折线点
                mLinePaint.setStyle(Paint.Style.FILL);
                mLinePaint.setColor(Color.WHITE);
                canvas.drawCircle(x, y, dp3, mLinePaint);
                mLinePaint.setStyle(Paint.Style.STROKE);
                mLinePaint.setColor(mLinecolor);
                canvas.drawCircle(x, y, dp3, mLinePaint);
                //绘制选中的点
                if (i == selectIndex - 1) {
                    mLinePaint.setStyle(Paint.Style.FILL);
                    mLinePaint.setColor(Color.WHITE);
                    canvas.drawCircle(x, y, dp5, mLinePaint);
                    mLinePaint.setColor(mContentColor);
                    mLinePaint.setStyle(Paint.Style.STROKE);
                    canvas.drawCircle(x, y, dp5, mLinePaint);
                    drawFloatTextBox(canvas, x, y - dp5, lineValues.get(i).value);
                }
            }
        }
    
        /**
         * 绘制点位信息弹出框
         */
        private void drawFloatTextBox(Canvas canvas, float x, float y, String text) {
            int dp6 = dpToPx(6);
            int dp20 = dpToPx(20);
            Path path = new Path();
            path.moveTo(x, y);
            path.lineTo(x - dp6, y - dp6);
            path.lineTo(x - dp20, y - dp6);
            path.lineTo(x - dp20, y - dp6 - dp20);
            path.lineTo(x + dp20, y - dp6 - dp20);
            path.lineTo(x + dp20, y - dp6);
            path.lineTo(x + dp6, y - dp6);
            path.lineTo(x, y);
            showPaint.setStyle(Paint.Style.FILL);
            canvas.drawPath(path, showPaint);
            //点位信息文字
            mLinePaint.setStyle(Paint.Style.FILL);
            mLinePaint.setColor(Color.WHITE);
            mLinePaint.setTextSize(dpToPx(13));
            Rect rect = getTextBounds(text + "", mLinePaint);
            canvas.drawText(text + "", x - rect.width() / 2, y - dp6 - (dp20 - rect.height()) / 2, mLinePaint);
        }
    
        /**
         * 绘制折线
         */
        private void drawBrokenLine(Canvas canvas) {
            mLinePaint.setStyle(Paint.Style.STROKE);
            mLinePaint.setColor(mLinecolor);
            //绘制折线
            Path path = new Path();
            float x = xInit + interval * 0;
            float y = (float) (yOrigin - yOrigin * (1 - 0.1f) * lineValues.get(0).num / yValues.get(yValues.size() - 1).num);
            path.moveTo(x, y);
            for (int i = 1; i < xValues.size(); i++) {
                x = xInit + interval * i;
                y = (float) (yOrigin - yOrigin * (1 - 0.1f) * lineValues.get(i).num / yValues.get(yValues.size() - 1).num);
                if (x < 0) x = 0;
                if (y < 0) y = 0;
                path.lineTo(x, y);
            }
            canvas.drawPath(path, mLinePaint);
        }
    

    这些就是绘制点与折线,还有信息框提示,接下来就是点击的事件, 如果我想查看某个数据点击就可以查看

    @Override
        public boolean onTouchEvent(MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_UP:
                    clickAction(event);
                    this.getParent().requestDisallowInterceptTouchEvent(false);
                    break;
                case MotionEvent.ACTION_CANCEL:
                    this.getParent().requestDisallowInterceptTouchEvent(false);
                    break;
            }
            return true;
        }
    
        /**
         * 点击X轴坐标或者折线节点
         *
         * @param event
         */
        private void clickAction(MotionEvent event) {
            int dp8 = dpToPx(8);
            float eventX = event.getX();
            float eventY = event.getY();
            for (int i = 0; i < xValues.size(); i++) {
                //节点
                float x = xInit + interval * i;
                float y = (float) (yOrigin - yOrigin * (1 - 0.1f) * lineValues.get(i).num / yValues.get(yValues.size() - 1).num);
                if (eventX >= x - dp8 && eventX <= x + dp8 &&
                        eventY >= y - dp8 && eventY <= y + dp8 && selectIndex != i + 1) {//每个节点周围8dp都是可点击区域
                    selectIndex = i + 1;
                    invalidate();
                    return;
                }
                //X轴刻度
                String text = xValues.get(i).value;
                Rect rect = getTextBounds(text, xyTextPaint);
                x = xInit + interval * i;
                y = yOrigin + mXYLineWidth + dpToPx(2);
                // 因为X轴上的字是80度角, 所以高度即时宽度
                if (eventX >= x - rect.height() / 2 - dp8 && eventX <= x + rect.height() + dp8 / 2 &&
                        eventY >= y - dp8 && eventY <= y + rect.width() + dp8 && selectIndex != i + 1) {
                    selectIndex = i + 1;
                    invalidate();
                    return;
                }
                // 这个是正常的文本点击事件
    //            if (eventX >= x - rect.width() / 2 - dp8 && eventX <= x + rect.width() + dp8 / 2 &&
    //                    eventY >= y - dp8 && eventY <= y + rect.height() + dp8 && selectIndex != i + 1) {
    //                selectIndex = i + 1;
    //                invalidate();
    //                return;
    //            }
            }
        }
    

    分为点 点击下面的月份点击, 如果不需要注释即可
    因为X轴上的字是80度角, 所以高度即时宽度,正常的文本点击事件要把宽高调过来

    public void setSelectIndex(int selectIndex) {
            this.selectIndex = selectIndex;
            invalidate();
        }
        
        public void setValue(List<LineValue> lineValues, List<XValue> xValues, List<YValue> yValues) {
            this.lineValues = lineValues;
            this.xValues = xValues;
            this.yValues = yValues;
            invalidate();
        }
    

    剩下的就是设置数据了, 设置点在哪个位置显示
    下面来看看使用 先看xml布局

          <com.dbz.example.BrokenLineView
                android:id="@+id/lineview"
                android:layout_width="match_parent"
                android:layout_height="220dp"
                app:dbz_bg_color="@android:color/white"
                app:dbz_content_color="#17894E"
                app:dbz_line_color="#17894E"
                app:dbz_xy_line_color="#cccccc"
                app:dbz_xy_line_width="1dp"
                app:dbz_xy_text_color="#494848"
                app:dbz_xy_text_size="13dp" />
    

    activity中的代码

    public class MainActivity extends AppCompatActivity {
        private List<BrokenLineView.XValue> xValues = new ArrayList();
        private List<BrokenLineView.YValue> yValues = new ArrayList();
        private List<BrokenLineView.LineValue> lineValues = new ArrayList();
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mBrokenLineView = findViewById(R.id.lineview);
            initView();
        }
    
        private void initView() {
           /**
             * 注意 我这里用的是随机数据, 当用接口返回的数据时  要取最大值设置数据, 但是Y轴也是最高值,
             * 这样在显示数据时 Y轴上点位信息数据会向上顶, 也就是说会顶的看不见 , 所以在绘制的时候,
             * Y轴的最大值要比真实的数据要大, 最好在最大值上乘以 百分之二十
             * 比如: 最大值是10   10 + 10 * 0.2
             */
            //模拟折线数据
            for (int i = 1; i <= 10; i++) {
                BrokenLineView.XValue xValue = new BrokenLineView.XValue(i, "3月" + i + "号");
                xValues.add(xValue);
                double value = new BigDecimal(Math.random() * 10).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                BrokenLineView.LineValue lineValue = new BrokenLineView.LineValue(value, value + "");
                lineValues.add(lineValue);
            }
            for (int i = 0; i <= 12; i++) {
                BrokenLineView.YValue yValue = new BrokenLineView.YValue(i, i + "");
                yValues.add(yValue);
            }
            mBrokenLineView.setValue(lineValues, xValues, yValues);
        }
    }
    

    下面是自定义的属性文件
    在values文件夹下面建一个attrs.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <declare-styleable name="brokenLineView">
            <!-- xy轴线颜色 -->
            <attr name="dbz_xy_line_color" format="color" />
            <!-- xy轴线的宽度 -->
            <attr name="dbz_xy_line_width" format="dimension" />
            <!-- xy轴上的文字颜色 -->
            <attr name="dbz_xy_text_color" format="color" />
            <!-- xy轴上的文字大小 -->
            <attr name="dbz_xy_text_size" format="dimension" />
            <!-- 折线的颜色 -->
            <attr name="dbz_line_color" format="color" />
            <!-- x轴坐标点间距 -->
            <attr name="dbz_interval" format="dimension" />
            <!-- 折线点位信息颜色 -->
            <attr name="dbz_content_color" format="color" />
            <!-- 背景颜色 -->
            <attr name="dbz_bg_color" format="color" />
        </declare-styleable>
    </resources>
    

    传送地址:https://github.com/xiaobinAndroid421726260/BrokenLineDemo.git

    相关文章

      网友评论

          本文标题:自定义折线图

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