1. 程式人生 > >Android 開發:繪製多條線,帶快取,帶觸控的圖表(基金圖表的實現)

Android 開發:繪製多條線,帶快取,帶觸控的圖表(基金圖表的實現)

對之前的幾篇文章裡的model進行補充
後期會把這個功能類,新增到這個框架裡 連結 Android開發框架,有興趣的可以下載下來看,這個框架會經常更新:
圖片描述

圖片描述

public class BaseFundChartView extends View implements View.OnTouchListener{

    Paint linePaint;
    Paint textPaint;
    Paint xyChartPaint;
    Paint chartLinePaint;
    Paint chartJianbianPaint;
    Paint huodongPaint;
    Paint huodongPaintText;
    List<Point> points;
    public
BaseFundChartView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public BaseFundChartView(Context context) { this(context, null); } public BaseFundChartView(Context context, AttributeSet attrs) { this
(context, attrs, 0); } PathEffect effect; Path path; private float getWidthYMax(){ return getWidth()-15; } private void init() { linePaint = new Paint(); textPaint = new Paint(); xyChartPaint = new Paint(); chartLinePaint = new Paint(); chartJianbianPaint = new
Paint(); huodongPaint = new Paint(); huodongPaintText = new Paint(); //設定繪製模式為-虛線作為背景線。 effect = new DashPathEffect(new float[] { 6, 6, 6, 6, 6}, 2); //背景虛線路徑. path = new Path(); //只是繪製的XY軸 linePaint.setStyle(Paint.Style.STROKE); // linePaint.setStrokeWidth((float) 0.7); linePaint.setStrokeWidth((float) 1.0); //設定線寬 linePaint.setColor(Color.BLACK); linePaint.setAntiAlias(true);// 鋸齒不顯示 //XY刻度上的字 textPaint.setStyle(Paint.Style.FILL);// 設定非填充 textPaint.setStrokeWidth(1);// 筆寬5畫素 textPaint.setColor(Color.BLACK);// 設定為藍筆 textPaint.setAntiAlias(true);// 鋸齒不顯示 textPaint.setTextAlign(Paint.Align.CENTER); textPaint.setTextSize(15); //繪製XY軸上的字:Y開關狀態、X時間 xyChartPaint.setStyle(Paint.Style.FILL); xyChartPaint.setStrokeWidth(1); xyChartPaint.setColor(Color.BLUE); xyChartPaint.setAntiAlias(true); xyChartPaint.setTextAlign(Paint.Align.CENTER); xyChartPaint.setTextSize(18); //繪製的折線 chartLinePaint.setStyle(Paint.Style.STROKE); chartLinePaint.setStrokeWidth(5); chartLinePaint.setColor(Color.BLUE); chartLinePaint.setAntiAlias(true); //繪製的折線 chartJianbianPaint.setStyle(Paint.Style.FILL); chartJianbianPaint.setStrokeWidth(5); //chartJianbianPaint.setColor(Color.YELLOW); chartJianbianPaint.setAntiAlias(true); huodongPaint.setStyle(Paint.Style.STROKE); huodongPaint.setStrokeWidth((float) 3.0); //設定線寬 huodongPaint.setColor(Color.GRAY); huodongPaint.setAntiAlias(true);// 鋸齒不顯示 huodongPaintText.setStyle(Paint.Style.STROKE); huodongPaintText.setStrokeWidth((float) 2.0); //設定線寬 huodongPaintText.setTextSize(40); huodongPaintText.setColor(Color.GRAY); huodongPaintText.setAntiAlias(true);// 鋸齒不顯示 setOnTouchListener(this); } private boolean refData = true; public void setRefData(boolean refData) { this.refData = refData; } /** * 重要引數,兩點之間分為幾段描畫,數字愈大分段越多,描畫的曲線就越精細. */ private static final int STEPS = 12; float gridX,gridY,xSpace = 0,ySpace = 0,spaceYT = 0; Float yStart=null,yStop = null; Integer yCount = null; List<String> text = null; public void setText(List<String> text) { this.text = text; } public void setyCount(Integer yCount) { this.yCount = yCount; } public void setyStart(Float yStart) { this.yStart = yStart; } public void setyStop(Float yStop) { this.yStop = yStop; } String yFormat=null; public void setFormat(String yFormat){ this.yFormat = yFormat; } List<String> dateX = null; List<Float> dateY = null; List<List<Float>> data = null; List<Integer> colors = null; public void setColors(List<Integer> colors) { this.colors = colors; } public List<Float> getDateY() { return dateY; } public void setDateY(List<Float> dateY) { this.dateY = dateY; } public List<List<Float>> getData() { return data; } public void setData(List<List<Float>> data) { this.data = data; } public List<String> getDateX() { return dateX; } public void setDateX(List<String> dateX) { this.dateX = dateX; } Map<Integer,List<Cubic>> mapCacheX = new HashMap<>(); Map<Integer,List<Cubic>> mapCacheY = new HashMap<>(); @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //基準點。 gridX = 40; gridY = getHeight() - 50; //XY間隔。 if(dateX!=null&&dateX.size()>0){ xSpace = (getWidthYMax() - gridX)/dateX.size(); } /** * 如果設定開頭和結尾的話,就直接生成y軸 */ if(yStart!=null&&yStop!=null&&yCount!=null){ dateY = new ArrayList<>(); ySpace = (gridY - 70)/yCount; float ze = (yStop-yStart)/yCount; for(int i=0;i<yCount;i++){ dateY.add(yStart+ze*i); } dateY.add(yStop); if(dateY.size()>2){ spaceYT = dateY.get(1)-dateY.get(0); } }else{ if(dateY!=null&&dateY.size()>0){ ySpace = (gridY - 70)/dateY.size(); yStart = dateY.get(0); if(dateY.size()>2){ spaceYT = dateY.get(1)-dateY.get(0); } } } UIUtils.log("rewqfdesa",gridY,"fdsafdsa"); //畫Y軸(帶箭頭)。 canvas.drawLine(gridX, gridY - 20 - 10, gridX, 10, linePaint); canvas.drawLine(gridX, 10, gridX - 6, 14 + 10, linePaint);//Y軸箭頭。 canvas.drawLine(gridX, 10, gridX + 6, 14 + 10, linePaint); //畫Y軸名字。 //由於是豎直顯示的,先以原點順時針旋轉90度後為新的座標系 //canvas.rotate(-90); //當xyChartPaint的setTextAlign()設定為center時第二、三個引數代表這四個字中點所在的xy座標 //canvas.drawText("開關狀態", -((float) (getHeight() - 60) - 15 - 5 - 1 / ((float) 1.6 * 1) * (getHeight() - 60) / 2), gridX - 15, xyChartPaint); //繪製Y軸座標 //canvas.rotate(90); //改變了座標系還要再改過來 float y = 0; //畫X軸。 y = gridY - 20; canvas.drawLine(gridX, y - 10, getWidthYMax(), y - 10, linePaint);//X軸. canvas.drawLine(getWidthYMax(), y - 10, getWidthYMax() - 14, y - 6 - 10, linePaint);//X軸箭頭。 canvas.drawLine(getWidthYMax(), y - 10, getWidthYMax() - 14, y + 6 - 10, linePaint); //繪製X刻度座標。 float x = 0; if(dateX!=null){ for (int n = 0; n < dateX.size(); n++) { //取X刻度座標. x = gridX + (n) * xSpace;//在原點(0,0)處也畫刻度(不畫的話就是n+1),向右移動一個跨度。 //畫X軸具體刻度值。 if (dateX.get(n) != null) { //canvas.drawLine(x, gridY - 30, x, gridY - 18, linePaint);//短X刻度。 canvas.drawText(dateX.get(n), x, gridY + 5, textPaint);//X具體刻度值。 } } } float my = 0; if(dateY!=null){ for(int n=0;n<dateY.size();n++){ //取Y刻度座標. my = gridY-30 - (n)*ySpace; UIUtils.log(my,"fdsafss",ySpace); //畫y軸具體刻度值。 float day = dateY.get(n); String dayForm = String.valueOf(day); if(yFormat!=null){ dayForm = TNum.getMoney(day,yFormat); } canvas.drawText(dayForm,gridX-15,my,textPaint); if(my != gridY-30){ linePaint.setPathEffect(effect);//設法虛線間隔樣式。 //畫除X軸之外的------背景虛線一條------- path.moveTo(gridX, my);//背景【虛線起點】。 path.lineTo(getWidthYMax(), my);//背景【虛線終點】。 canvas.drawPath(path, linePaint); } } } if(data!=null&&data.size()>0){ float lastPointX = 0; //前一個點 float lastPointY = 0; float currentPointX = 0;//當前點 float currentPointY = 0; for(int n=0;n<data.size();n++){ List<Float> da = data.get(n); List<Float> da_x = new ArrayList<>(); List<Float> da_y = new ArrayList<>(); /** * 曲線路勁 */ Path curvePath = new Path(); /** * 漸變色路徑 */ Path jianBianPath = new Path(); List<Cubic> calculate_y; List<Cubic> calculate_x; if(refData){ for(int m=0;m<da.size();m++){ currentPointX = m * xSpace + gridX; currentPointY = gridY-30 - ((da.get(m)-yStart)*(ySpace/spaceYT)); da_x.add(currentPointX); da_y.add(currentPointY); // if(m>0){ // canvas.drawLine(lastPointX, lastPointY, currentPointX, currentPointY, chartLinePaint); // } // lastPointX = currentPointX; // lastPointY = currentPointY; } calculate_y = calculate(da_y); calculate_x = calculate(da_x); mapCacheY.put(n,calculate_y); mapCacheX.put(n,calculate_x); if(n>=data.size()-1){ refData = false; } }else{ calculate_y = mapCacheY.get(n); calculate_x = mapCacheX.get(n); } curvePath.moveTo(calculate_x.get(0).eval(0), calculate_y.get(0).eval(0)); jianBianPath.moveTo(gridX,gridY - 20 - 10); jianBianPath.lineTo(calculate_x.get(0).eval(0), calculate_y.get(0).eval(0)); chartLinePaint.setColor(colors.get(n)); float lastx = 0; for (int i = 0; i < calculate_x.size(); i++) { for (int j = 1; j <= STEPS; j++) { float u = j / (float) STEPS; curvePath.lineTo(calculate_x.get(i).eval(u), calculate_y.get(i) .eval(u)); jianBianPath.lineTo(calculate_x.get(i).eval(u), calculate_y.get(i) .eval(u)); lastx = calculate_x.get(i).eval(u); } } jianBianPath.lineTo(lastx,gridY - 20 - 10); canvas.drawPath(curvePath, chartLinePaint); Shader mShader = new LinearGradient(0,30 + 10,0,gridY - 20 - 10,new int[] {colors.get(n),Color.TRANSPARENT},null,Shader.TileMode.REPEAT); //新建一個線性漸變,前兩個引數是漸變開始的點座標,第三四個引數是漸變結束的點的座標。連線這2個點就拉出一條漸變線了,玩過PS的都懂。然後那個陣列是漸變的顏色。下一個引數是漸變顏色的分佈,如果為空,每個顏色就是均勻分佈的。最後是模式,這裡設定的是迴圈漸變 chartJianbianPaint.setShader(mShader); canvas.drawPath(jianBianPath, chartJianbianPaint); } } if(lineX!=null){ if(text!=null&&text.size()>0){ Paint.FontMetrics metrics = huodongPaintText.getFontMetrics(); float top = metrics.top; float bootom = metrics.bottom; float h = bootom-top; float th = h + h*text.size(); float w=0; float fx = 1; if(lineX>getWidth()/2){ fx = -1; }else{ fx = 1; } for(int i=0;i<text.size();i++){ Rect rect = new Rect(); huodongPaintText.getTextBounds(text.get(i), 0, text.get(i).length(), rect); int width = rect.width();//文字的寬度 if(width>w){ w = width; } canvas.drawText(text.get(i),fx==1?lineX+10:lineX-10-width,40+ h*(i+1),huodongPaintText); } canvas.drawLine(lineX, gridY - 20 - 10, lineX, 30 + 10, huodongPaint); //canvas.drawRect(lineX,40,lineX+w*fx+20*fx,40+th,huodongPaint); } } } /** * 計算曲線. * * @param x * @return */ private List<Cubic> calculate(List<Float> x) { int n = x.size() - 1; float[] gamma = new float[n + 1]; float[] delta = new float[n + 1]; float[] D = new float[n + 1]; int i; /* * We solve the equation [2 1 ] [D[0]] [3(x[1] - x[0]) ] |1 4 1 | |D[1]| * |3(x[2] - x[0]) | | 1 4 1 | | . | = | . | | ..... | | . | | . | | 1 4 * 1| | . | |3(x[n] - x[n-2])| [ 1 2] [D[n]] [3(x[n] - x[n-1])] * * by using row operations to convert the matrix to upper triangular and * then back sustitution. The D[i] are the derivatives at the knots. */ gamma[0] = 1.0f / 2.0f; for (i = 1; i < n; i++) { gamma[i] = 1 / (4 - gamma[i - 1]); } gamma[n] = 1 / (2 - gamma[n - 1]); delta[0] = 3 * (x.get(1) - x.get(0)) * gamma[0]; for (i = 1; i < n; i++) { delta[i] = (3 * (x.get(i + 1) - x.get(i - 1)) - delta[i - 1]) * gamma[i]; } delta[n] = (3 * (x.get(n) - x.get(n - 1)) - delta[n - 1]) * gamma[n]; D[n] = delta[n]; for (i = n - 1; i >= 0; i--) { D[i] = delta[i] - gamma[i] * D[i + 1]; } /* now compute the coefficients of the cubics */ List<Cubic> cubics = new LinkedList<Cubic>(); for (i = 0; i < n; i++) { Cubic c = new Cubic(x.get(i), D[i], 3 * (x.get(i + 1) - x.get(i)) - 2 * D[i] - D[i + 1], 2 * (x.get(i) - x.get(i + 1)) + D[i] + D[i + 1]); cubics.add(c); } return cubics; } Float lineX = null; Integer temp = null; @Override public boolean onTouch(View v, MotionEvent event) { getParent().requestDisallowInterceptTouchEvent(true); switch(event.getAction()){ case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: float zhi = (event.getX()-gridX)%xSpace; boolean fanwei = zhi>0&&zhi<xSpace; if(xSpace!=0&&(event.getX() - gridX )>0&&fanwei&&event.getX()<getWidthYMax()){ UIUtils.log("觸控到了"); int x = (int)((event.getX() - gridX )/xSpace); lineX = gridX + x*xSpace; if(temp!=null&&temp.equals(x)){ UIUtils.log("不重新整理"); return true; } UIUtils.log("重新整理"); temp = x; if(onFundChat!=null){ onFundChat.onRefChatText(this,x); } invalidate(); } break; } return true; } OnFundChat onFundChat = null; public interface OnFundChat{ void onRefChatText(BaseFundChartView view,int x); } public void setOnFundChat(OnFundChat onFundChat) { this.onFundChat = onFundChat; } class Cubic{ float a,b,c,d; /* a + b*u + c*u^2 +d*u^3 */ public Cubic(float a, float b, float c, float d){ this.a = a; this.b = b; this.c = c; this.d = d; } /** evaluate cubic */ public float eval(float u) { return (((d*u) + c)*u + b)*u + a; } } }