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

2017-05-31  本文已影响0人  打不垮的墙

相信在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;

/**

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

上一篇下一篇

猜你喜欢

热点阅读