Android简单自定义折线图(自定义view实现)

相信在Android开发中或多或少都会遇到“ 图表 “”类的展示,当然首推大神的MPAndroidChart ,github:https://github.com/PhilJay/MPAndroidChart

但有时候仅仅是为了融合UI设计,所需功能也并不复杂,复用性也一般,MPAndroidChart 就有点大材小用了,并且也会增加了项目的体量,最近群里的朋友有需求,就花点时间通过自定义View写了一个,在此分享给大家:

我的视频 8_clip.gif

Demo地址:http://pan.baidu.com/s/1skKQxv3
<pre>
package com.example.cloud.zqchart;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.TreeMap;
import java.util.TreeSet;

/**

  • Created by CLOUD on 2017/5/27.
    */

public class ZqChart extends View {
private Paint mPaintbg;
private Paint mPaintMonthbg;
private Paint mPaintLine;
private Paint mPaintText;
private Paint mPaintChoose;
private Paint mPaintTouch;
private int defaultWidth;
private int defaultUnitHeight;
List<Chart> datas;
TreeSet<Chart> months;
private int mChooseMonth;

private List<Chart> mDatasSingle;
private Chart mTouch;
private float lastX;
private float mDMoneyRateW;
private int mMeasuredWidth;



public ZqChart(Context context) {
    super(context);
    init();
}


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

public ZqChart(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

private void init() {
    mPaintbg = new Paint();
    mPaintbg.setAntiAlias(true);
    mPaintbg.setStyle(Paint.Style.FILL);
    mPaintbg.setColor(Color.DKGRAY);
    mPaintMonthbg = new Paint();
    mPaintMonthbg.setAntiAlias(true);
    mPaintMonthbg.setStyle(Paint.Style.FILL);
    mPaintMonthbg.setColor(Color.BLACK);

    mPaintLine = new Paint();
    mPaintLine.setAntiAlias(true);
    mPaintLine.setStyle(Paint.Style.STROKE);
    mPaintLine.setColor(Color.WHITE);
    mPaintTouch = new Paint();
    mPaintTouch.setAntiAlias(true);
    mPaintTouch.setStyle(Paint.Style.STROKE);
    mPaintTouch.setStrokeWidth(3);
    mPaintTouch.setColor(Color.WHITE);

    mPaintText = new Paint();
    mPaintText.setAntiAlias(true);
    mPaintText.setStyle(Paint.Style.FILL);
    mPaintText.setColor(Color.WHITE);
    mPaintText.setTextSize(25);

    mPaintChoose = new Paint();
    mPaintChoose.setAntiAlias(true);
    mPaintChoose.setStyle(Paint.Style.FILL);
    mPaintChoose.setColor(Color.WHITE);

    months=new TreeSet<>(new Comparator<Chart>() {
        @Override
        public int compare(Chart o1, Chart o2) {
            return o1.getDateMonth()-o2.getDateMonth();
        }
    });

    defaultWidth=dip2px(getContext(),200);
    defaultUnitHeight=dip2px(getContext(),25);

    mChooseMonth=2;
    mDatasSingle = new ArrayList<>();
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int widthmode = MeasureSpec.getMode(widthMeasureSpec);
    int heightmode = MeasureSpec.getMode(heightMeasureSpec);
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);

    if (datas!=null&&datas.size()>0){

        for (Chart data : datas) {
            months.add(data);
        }
        if (widthmode==MeasureSpec.AT_MOST){

            width=defaultWidth;
        }
        if (heightmode==MeasureSpec.AT_MOST){
            height= (int) (defaultUnitHeight*months.size()*1.5);
        }
    }

    setMeasuredDimension(width,height);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    int measuredHeight = getMeasuredHeight();
    mMeasuredWidth = getMeasuredWidth();
    Rect rect = new Rect(0,0, mMeasuredWidth,measuredHeight);
    canvas.save();
    canvas.clipRect(rect);
    canvas.drawRect(rect,mPaintbg);
    Rect bounds = new Rect();
    mPaintText.getTextBounds("01月",0,"01月".length(), bounds);
    int xUnit=(mMeasuredWidth -bounds.width()*3)/6;
    for (int i = 1; i <=6; i++) {
        String day=""+new DecimalFormat("#00").format(i*5);
        canvas.drawText(day,i*xUnit,measuredHeight-bounds.height(),mPaintText);
    }
    int count=1;
    for (Chart month : months) {
        String day=""+new DecimalFormat("#00").format(month.getDateMonth());
        if (month.getDateMonth()==mChooseMonth){
            mPaintMonthbg.setColor(Color.RED);
        }else {
            mPaintMonthbg.setColor(Color.BLACK);
        }

        RectF oval = new RectF(
                mMeasuredWidth - bounds.width() * 2 - bounds.width() / 2,
                measuredHeight - bounds.height() - count * defaultUnitHeight - bounds.height(),
                mMeasuredWidth - bounds.width() * 2 + bounds.width(),
                measuredHeight - bounds.height() - count * defaultUnitHeight + bounds.height() / 2
        );
        canvas.drawOval(oval,mPaintMonthbg);
        canvas.drawText(day, mMeasuredWidth -bounds.width()*2,measuredHeight-bounds.height()-count*defaultUnitHeight,mPaintText);
        month.setMonthAres(oval);
        count++;
    }
    if (mChooseMonth==0){
        canvas.restore();
        return;
    }


    if (mDatasSingle.size()==0){
        canvas.restore();
        return;
    }

    float minMoney= mDatasSingle.get(0).getMoney();
    float maxMoney= mDatasSingle.get(0).getMoney();
    for (Chart data : mDatasSingle) {
        minMoney=data.getMoney()<minMoney?data.getMoney():minMoney;
        maxMoney=data.getMoney()>maxMoney?data.getMoney():maxMoney;
    }
   float dMoneyRateH=months.size()*defaultUnitHeight/(maxMoney-minMoney);
    mDMoneyRateW = 6*xUnit/(30);
    if (mDatasSingle.size()==1){
        canvas.drawPoint(mDatasSingle.get(0).getDateDay()* mDMoneyRateW,measuredHeight-bounds.height()-(mDatasSingle.get(0).getMoney()-minMoney)*dMoneyRateH,mPaintLine);
        canvas.restore();
        return;
    }
    Path path=new Path();
    Collections.sort(mDatasSingle, new Comparator<Chart>() {
        @Override
        public int compare(Chart o1, Chart o2) {
            return o1.getDateDay()-o2.getDateDay();
        }
    });
    float starX = mDatasSingle.get(0).getDateDay() * mDMoneyRateW;
    float starY = measuredHeight - bounds.height()*2 - (mDatasSingle.get(0).getMoney()-minMoney) * dMoneyRateH;
    path.moveTo(starX, starY);
    mDatasSingle.get(0).pointX=starX;
    mDatasSingle.get(0).pointY=starY;
    mDatasSingle.get(0).ares=new RectF(starX- mDMoneyRateW /2,measuredHeight-bounds.height()-months.size()*defaultUnitHeight,starX+ mDMoneyRateW /2,measuredHeight-bounds.height());
    for (int i = 1; i < mDatasSingle.size(); i++) {
        float x = mDatasSingle.get(i).getDateDay() * mDMoneyRateW;
        float y = measuredHeight - bounds.height()*2 - (mDatasSingle.get(i).getMoney()-minMoney) * dMoneyRateH;
        path.lineTo(x, y);
        mDatasSingle.get(i).pointX=x;
        mDatasSingle.get(i).pointY=y;
        mDatasSingle.get(i).ares=new RectF(x- mDMoneyRateW /2,measuredHeight-bounds.height()-months.size()*defaultUnitHeight,x+ mDMoneyRateW /2,measuredHeight-bounds.height());
        Log.e("mDatasSingle","ares:"+ mDatasSingle.get(i).ares);
    }
    canvas.drawPath(path,mPaintLine);

if (mTouch!=null){
canvas.drawLine(mTouch.pointX, measuredHeight - bounds.height()2,mTouch.pointX, measuredHeight - bounds.height()4-months.size()defaultUnitHeight,mPaintTouch);
canvas.drawCircle(mTouch.pointX,mTouch.pointY,Math.max(bounds.height(),bounds.width())/2,mPaintbg);
canvas.drawCircle(mTouch.pointX,mTouch.pointY,Math.max(bounds.height(),bounds.width())/2,mPaintTouch);
String day=""+new DecimalFormat("#00").format(mTouch.getDateDay());
canvas.drawText( day,mTouch.pointX-bounds.width()/3,mTouch.pointY+bounds.height()/2,mPaintText);
Path pathValue=new Path();
pathValue.moveTo(mTouch.pointX,measuredHeight - bounds.height()
4-months.size()defaultUnitHeight);
float money = mTouch.getMoney();
Rect rectMonet = new Rect();
mPaintText.getTextBounds(money+"",0,(money+"").length(), rectMonet);
pathValue.lineTo(mTouch.pointX-rectMonet.width()/2,measuredHeight - bounds.height()
4-months.size()defaultUnitHeight);
pathValue.quadTo(mTouch.pointX-rectMonet.width()
1.0f,measuredHeight - bounds.height()4-months.size()defaultUnitHeight-rectMonet.height()
,mTouch.pointX-rectMonet.width()/2,measuredHeight - bounds.height()4-months.size()defaultUnitHeight-rectMonet.height()2);
pathValue.lineTo(mTouch.pointX+rectMonet.width()/2,measuredHeight - bounds.height()
4-months.size()defaultUnitHeight-rectMonet.height()2);
pathValue.quadTo(mTouch.pointX+rectMonet.width()1.0f,measuredHeight - bounds.height()4-months.size()defaultUnitHeight-rectMonet.height()
,mTouch.pointX+rectMonet.width()/2,measuredHeight - bounds.height()
4-months.size()defaultUnitHeight);
pathValue.lineTo(mTouch.pointX,measuredHeight - bounds.height()
4-months.size()defaultUnitHeight);
canvas.drawPath(pathValue,mPaintTouch);
canvas.drawText(money+"",mTouch.pointX-rectMonet.width()/2,measuredHeight - bounds.height()
4-months.size()*defaultUnitHeight-rectMonet.height()/2,mPaintText);
}

    canvas.restore();

}

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()){
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
            float x = event.getX();
            float y = event.getY();

            if (lastX==0||Math.abs(lastX-x)>mDMoneyRateW){
                Log.e("onTouchEvent","x:"+x);
                Log.e("onTouchEvent","y:"+y);
                for (Chart chart : mDatasSingle) {
                    boolean contains = chart.ares.contains(x, y);
                    if (contains){
                        mTouch=chart;
                        invalidate();
                        break;
                    }
                }
                lastX =x;
            }


            break;
        case MotionEvent.ACTION_UP:
            float xUp = event.getX();
            float yUp = event.getY();
            if (xUp>6*mDMoneyRateW&&xUp<mMeasuredWidth){
                for (Chart month : months) {
                    RectF monthAres = month.getMonthAres();
                    if (monthAres.contains(xUp,yUp)){
                        setChooseMonth(month.getDateMonth());
                    }
                }
            }
            break;
    }

    return true;
}

/**
 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
 */
public  int dip2px(Context context, float dpValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dpValue * scale + 0.5f);
}

public void setDatas(List<Chart> datas) {
    this.datas = datas;
    mDatasSingle.clear();
    for (Chart data : datas) {
        if (data.getDateMonth()==mChooseMonth)
            mDatasSingle.add(data);
    }
    invalidate();
}

public void setChooseMonth(int chooseMonth) {
    mChooseMonth = chooseMonth;
    mTouch=null;
    mDatasSingle.clear();
    for (Chart data : datas) {
        if (data.getDateMonth()==mChooseMonth)
            mDatasSingle.add(data);
    }
    invalidate();
}

}

</pre>

Demo地址;http://pan.baidu.com/s/1skKQxv3

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

推荐阅读更多精彩内容