Android自定义折线图

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

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/Android_CustomAllCollection.git

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,012评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,589评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,819评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,652评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,954评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,381评论 1 210
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,687评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,404评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,082评论 1 238
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,355评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,880评论 1 255
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,249评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,864评论 3 232
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,007评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,760评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,394评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,281评论 2 259

推荐阅读更多精彩内容