Android 折线图 教你自定义折线图

先看图
BrokenLine.png
分析图表

首先我们根据上图我们可以看到如下几个元素

  • 边框线

![5FXGL_@$E{Y)R{}L~1V$]7R.png](http://upload-images.jianshu.io/upload_images/6544862-a5cc5c5619226bea.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

  • 边框线数据值
BrokenLineData.png
  • 边框线内折线
Line.png
  • 折线上的圆
如上分析,我们所需要绘制的就是边框线,框线分段数据值,框内折线,折线上的圆

在画图之前 我们首先得 准备一些 必要参数

<code>

/**View宽度*/
private int mViewWidth;
/** View高度*/
private int mViewHeight;
/**边框线画笔*/
private Paint mBorderLinePaint;
/**文本画笔*/
private Paint mTextPaint;
/**要绘制的折线线画笔*/
private Paint mBrokenLinePaint;
/**圆画笔*/
private Paint mCirclePaint;
/**圆的半径*/
private float radius=5;
/**边框的左边距*/
private float mBrokenLineLeft=40;
/**边框的上边距*/
private float mBrokenLineTop=40;
/**边框的下边距*/
private float mBrokenLineBottom=40;
/**边框的右边距*/
private float mBrokenLinerRight=20;
/**需要绘制的宽度*/
private float mNeedDrawWidth;
/**需要绘制的高度*/
private float mNeedDrawHeight;
/**边框文本*/
private int[] valueText =new int[]{40,30,20,10,0};
/**数据值*/
private int[] value=new int[]{11,10,15,12,34,12,22,23,33,13};

/**图表的最大值*/
private int maxVlaue=40;

</code>

参数准备好 首先 重写onMeasure 初始化参数

<code>

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    mViewHeight = getMeasuredHeight();
    mViewWidth = getMeasuredWidth();
    initNeedDrawWidthAndHeight();
    initPaint();
}



/**初始化绘制折线图的宽高*/
private void initNeedDrawWidthAndHeight(){
    mNeedDrawWidth = mViewWidth-mBrokenLineLeft-mBrokenLinerRight;
    mNeedDrawHeight = mViewHeight-mBrokenLineTop-mBrokenLineBottom;
}

 /**初始化画笔*/
private void initPaint() {

    /**初始化文本画笔*/
    if(mTextPaint==null){
        mTextPaint=new Paint();
    }
    initPaint(mTextPaint);

    /**初始化边框线画笔*/
    if(mBorderLinePaint==null){
        mBorderLinePaint=new Paint();
        mBorderLinePaint.setTextSize(20);
    }
    initPaint(mBorderLinePaint);

    /**初始化折线画笔*/
    if(mBrokenLinePaint==null){
        mBrokenLinePaint=new Paint();
    }
    initPaint(mBrokenLinePaint);

    if(mCirclePaint==null){
        mCirclePaint=new Paint();
    }
    initPaint(mCirclePaint);
}

/**初始化画笔默认属性*/
private void initPaint(Paint paint){
    paint.setAntiAlias(true);
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(Color.BLACK);
}

</code>

这个时候我们的一切参数 都准备好了 首先我们来完成边线框的绘制

![5FXGL_@$E{Y)R{}L~1V$]7R.png](http://upload-images.jianshu.io/upload_images/6544862-a5cc5c5619226bea.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<code>

 /**绘制边框竖线*/
    canvas.drawLine(mBrokenLineLeft,mBrokenLineTop-10,mBrokenLineLeft,mViewHeight-mBrokenLineBottom,mBorderLinePaint);
    /**绘制边框横线*/
    canvas.drawLine(mBrokenLineLeft,mViewHeight-mBrokenLineBottom,mViewWidth,mViewHeight-mBrokenLineBottom,mBorderLinePaint);

</code>

边线框值的绘制
BrokenLineData.png

<code>

    /**绘制边线框的值*/
    float averageHeight=mNeedDrawHeight/(valueText.length-1);
    mBorderLinePaint.setTextAlign(Paint.Align.RIGHT);
    mBorderLinePaint.setColor(Color.GRAY);
    for (int i = 0; i < valueText.length; i++) {
        float nowadayHeight= averageHeight*i;
        canvas.drawLine(mBrokenLineLeft,nowadayHeight+mBrokenLineTop,mViewWidth-mBrokenLinerRight,nowadayHeight+mBrokenLineTop,mBorderLinePaint);
        canvas.drawText(valueText[i]+"",mBrokenLineLeft-5,nowadayHeight+mBrokenLineTop,mBorderLinePaint);
    }

</code>

绘制框内的线
Line.png

<code>

/**根据值绘制折线*/
private void DrawBrokenLine(Canvas canvas) {
    Path mPath=new Path();
    mBrokenLinePaint.setColor(Color.BLUE);
    mBrokenLinePaint.setStrokeWidth(2);
    Point[] points= getPoints(value,mNeedDrawHeight,mNeedDrawWidth,maxVlaue,mBrokenLineLeft,mBrokenLineTop);
    for (int i = 0; i < points.length; i++) {
        Point point=points[i];
        if(i==0){
            mPath.moveTo(point.x,point.y);
        }else {
            mPath.lineTo(point.x,point.y);
        }

    }
    canvas.drawPath(mPath,mBrokenLinePaint);
}


/**根据值计算在该值的 x,y坐标*/
public Point[] getPoints(int[] values, float height, float width, int max , float left,float top) {
    float leftPading = width / (values.length-1);//绘制边距
    Point[] points = new Point[values.length];
    for (int i = 0; i < values.length; i++) {
        float value = values[i];
        //计算每点高度所以对应的值
        double mean = (double) max/height;
        //获取要绘制的高度
        float drawHeight = (float) (value / mean);
        int pointY = (int) (height+top  - drawHeight);
        int pointX = (int) (leftPading * i + left);
        Point point = new Point(pointX, pointY);
        points[i] = point;
    }
    return points;
}

</code>

绘制线上的圆

<code>

/**绘制线上的圆*/
private void DrawLineCircle(Canvas canvas) {
    Point[] points= getPoints(value,mNeedDrawHeight,mNeedDrawWidth,maxVlaue,mBrokenLineLeft,mBrokenLineTop);
    for (int i = 0; i <points.length ; i++) {
        Point point=points[i];
        mCirclePaint.setColor(Color.WHITE);
        mCirclePaint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(point.x,point.y,radius,mCirclePaint);
        mCirclePaint.setColor(Color.BLUE);
        mCirclePaint.setStyle(Paint.Style.STROKE);
        mCirclePaint.setStrokeWidth(3);
        /**
         * drawCircle(float cx, float cy, float radius, Paint paint)
         * cx 中间x坐标
         * xy 中间y坐标
         * radius 圆的半径
         * paint 绘制圆的画笔
         * */
        canvas.drawCircle(point.x,point.y,radius,mCirclePaint);

    }
}

</code>

那么完整的代码如下

<code>

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;


public class BrokenLineChart extends View {
    private static final String TAG = "BrokenLineChart";
    /**View宽度*/
    private int mViewWidth;
    /** View高度*/
    private int mViewHeight;
    /**边框线画笔*/
    private Paint mBorderLinePaint;
    /**文本画笔*/
    private Paint mTextPaint;
    /**要绘制的折线线画笔*/
    private Paint mBrokenLinePaint;
    /**圆画笔*/
    private Paint mCirclePaint;
    /**圆的半径*/
    private float radius=5;
    /**边框的左边距*/
    private float mBrokenLineLeft=40;
    /**边框的上边距*/
    private float mBrokenLineTop=40;
    /**边框的下边距*/
    private float mBrokenLineBottom=40;
    /**边框的右边距*/
    private float mBrokenLinerRight=20;
    /**需要绘制的宽度*/
    private float mNeedDrawWidth;
    /**需要绘制的高度*/
    private float mNeedDrawHeight;
    /**边框文本*/
    private int[] valueText =new int[]{40,30,20,10,0};
    /**数据值*/
    private int[] value=new int[]{11,10,15,12,34,12,22,23,33,13};

    /**图表的最大值*/
    private int maxVlaue=40;
    public BrokenLineChart(Context context) {
        super(context);
    }

    public BrokenLineChart(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mViewHeight = getMeasuredHeight();
        mViewWidth = getMeasuredWidth();
        initNeedDrawWidthAndHeight();
        initPaint();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        /**绘制边框线和边框文本*/
        DrawBorderLineAndText(canvas);

        /**根据数据绘制线*/
        DrawBrokenLine(canvas);
        DrawLineCircle(canvas);



    }
    /**绘制线上的圆*/
    private void DrawLineCircle(Canvas canvas) {
        Point[] points= getPoints(value,mNeedDrawHeight,mNeedDrawWidth,maxVlaue,mBrokenLineLeft,mBrokenLineTop);
        for (int i = 0; i <points.length ; i++) {
            Point point=points[i];
            mCirclePaint.setColor(Color.WHITE);
            mCirclePaint.setStyle(Paint.Style.FILL);
            canvas.drawCircle(point.x,point.y,radius,mCirclePaint);
            mCirclePaint.setColor(Color.BLUE);
            mCirclePaint.setStyle(Paint.Style.STROKE);
            mCirclePaint.setStrokeWidth(3);
            /**
             * drawCircle(float cx, float cy, float radius, Paint paint)
             * cx 中间x坐标
             * xy 中间y坐标
             * radius 圆的半径
             * paint 绘制圆的画笔
             * */
            canvas.drawCircle(point.x,point.y,radius,mCirclePaint);

        }
    }

    /**根据值绘制折线*/
    private void DrawBrokenLine(Canvas canvas) {
        Path mPath=new Path();
        mBrokenLinePaint.setColor(Color.BLUE);
        mBrokenLinePaint.setStrokeWidth(2);
        Point[] points= getPoints(value,mNeedDrawHeight,mNeedDrawWidth,maxVlaue,mBrokenLineLeft,mBrokenLineTop);
        for (int i = 0; i < points.length; i++) {
            Point point=points[i];
            if(i==0){
                mPath.moveTo(point.x,point.y);
            }else {
                mPath.lineTo(point.x,point.y);
            }

        }
        canvas.drawPath(mPath,mBrokenLinePaint);
    }

    /**绘制边框线和边框文本*/
    private void DrawBorderLineAndText(Canvas canvas) {
        /**对应的属性
         * drawLine(float startX, float startY, float stopX, float stopY, Paint paint);
         * startX   开始的x坐标
         * startY   开始的y坐标
         * stopX    结束的x坐标
         * stopY    结束的y坐标
         * paint    绘制该线的画笔
         * */
        mBorderLinePaint.setColor(Color.BLACK);
        /**绘制边框竖线*/
        canvas.drawLine(mBrokenLineLeft,mBrokenLineTop-10,mBrokenLineLeft,mViewHeight-mBrokenLineBottom,mBorderLinePaint);
        /**绘制边框横线*/
        canvas.drawLine(mBrokenLineLeft,mViewHeight-mBrokenLineBottom,mViewWidth,mViewHeight-mBrokenLineBottom,mBorderLinePaint);


        /**绘制边框分段横线与分段文本*/
        float averageHeight=mNeedDrawHeight/(valueText.length-1);
        mBorderLinePaint.setTextAlign(Paint.Align.RIGHT);
        mBorderLinePaint.setColor(Color.GRAY);
        for (int i = 0; i < valueText.length; i++) {
            float nowadayHeight= averageHeight*i;
            canvas.drawLine(mBrokenLineLeft,nowadayHeight+mBrokenLineTop,mViewWidth-mBrokenLinerRight,nowadayHeight+mBrokenLineTop,mBorderLinePaint);
            canvas.drawText(valueText[i]+"",mBrokenLineLeft-5,nowadayHeight+mBrokenLineTop,mBorderLinePaint);
        }

    }

    /**初始化画笔*/
    private void initPaint() {

        /**初始化文本画笔*/
        if(mTextPaint==null){
            mTextPaint=new Paint();
        }
        initPaint(mTextPaint);

        /**初始化边框线画笔*/
        if(mBorderLinePaint==null){
            mBorderLinePaint=new Paint();
            mBorderLinePaint.setTextSize(20);
        }
        initPaint(mBorderLinePaint);

        /**初始化折线画笔*/
        if(mBrokenLinePaint==null){
            mBrokenLinePaint=new Paint();
        }
        initPaint(mBrokenLinePaint);

        if(mCirclePaint==null){
            mCirclePaint=new Paint();
        }
        initPaint(mCirclePaint);
    }

    /**初始化画笔默认属性*/
    private void initPaint(Paint paint){
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.BLACK);
    }


    /**初始化绘制折线图的宽高*/
    private void initNeedDrawWidthAndHeight(){
        mNeedDrawWidth = mViewWidth-mBrokenLineLeft-mBrokenLinerRight;
        mNeedDrawHeight = mViewHeight-mBrokenLineTop-mBrokenLineBottom;
    }
    /**根据值计算在该值的 x,y坐标*/
    public Point[] getPoints(int[] values, float height, float width, int max , float left,float top) {
        float leftPading = width / (values.length-1);//绘制边距
        Point[] points = new Point[values.length];
        for (int i = 0; i < values.length; i++) {
            float value = values[i];
            //计算每点高度所以对应的值
            double mean = (double) max/height;
            //获取要绘制的高度
            float drawHeight = (float) (value / mean);
            int pointY = (int) (height+top  - drawHeight);
            int pointX = (int) (leftPading * i + left);
            Point point = new Point(pointX, pointY);
            points[i] = point;
        }
        return points;
    }
}

</code>

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

推荐阅读更多精彩内容