Android開發自定義控制元件實現一個折線圖

王世暉發表於2016-05-18

實現一個如下圖所示的折線圖



首先是控制元件繪圖區域的劃分,控制元件左邊取一小部分(控制元件總寬度的八分之一)繪製表頭,右邊剩餘的部分繪製表格

確定表格的行列數,首先繪製一個三行八列的網格,設定好行列的座標後開始繪製

/*繪製三條橫線*/
for(int i=0;i<3;i++){
    canvas.drawLine(textWide, mLineYs[i], totalWidth, mLineYs[i], mPaintLine);
}
/*繪製八條豎線*/
for(int i=0;i<8;i++){
    canvas.drawLine(mLineXs[i], 0, mLineXs[i], totalHeight, mPaintLine);
}

網格繪製完成後,開始繪製折線圖

根據輸入的節點資料,分別繪製兩條折線

通過canvas的drawLine方法依次連線兩點即可

在每個資料節點處繪製一個小圓,突出顯示

/*繪製第一條折線的路徑*/
for (int i = 0; i < mPerformance_1.length - 1; i++) {
    /*折線圖的折線的畫筆設定粗一點*/
    mPaintLine.setStrokeWidth(5);
    /*計算當前節點的座標值*/
    float prePointX =mLineXs[i];
    float prePointY =mLineYs[2] - (mLineYs[2] - mLineYs[mPerformance_1[i].type]) * animCurrentValue;
    /*計算下一個節點的座標值*/
    float nextPointX=mLineXs[i + 1];
    float nextPointY=mLineYs[2] - (mLineYs[2] - mLineYs[mPerformance_1[i + 1].type]) * animCurrentValue;
    /*連線當前座標和下一個座標,繪製線段*/
    canvas.drawLine(prePointX, prePointY, nextPointX, nextPointY, mPaintLine1);
    /*當前節點座標處繪製小圓*/
    canvas.drawCircle(prePointX, prePointY, mSmallDotRadius, mPointPaint);
}

兩條折線重合的地方,需要特殊考慮,比如希望兩條折線重合的地方折線變為白色

設定下兩條折線的畫筆即可

mPaintLine2.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SCREEN));
mPaintLine1.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SCREEN));



測試程式碼及效果;

final Random random=new Random();
final LineChartView myView=(LineChartView)findViewById(R.id.custom_view);
final LineChartView.Performance[] performances1=new LineChartView.Performance[8];
final LineChartView.Performance[] performances2=new LineChartView.Performance[8];
myView.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View v){
        for(int i=0;i<performances1.length;i++){
            switch (random.nextInt(2016)%3){
                case 0:
                    performances1[i]= LineChartView.Performance.WIN;
                    break;
                case 1:
                    performances1[i]= LineChartView.Performance.DRAW;
                    break;
                case 2:
                    performances1[i]= LineChartView.Performance.LOSE;
                    break;
                default:
                    performances1[i]= LineChartView.Performance.LOSE;
                    break;
            }
            switch (random.nextInt(2016)%3){
                case 0:
                    performances2[i]= LineChartView.Performance.WIN;
                    break;
                case 1:
                    performances2[i]= LineChartView.Performance.DRAW;
                    break;
                case 2:
                    performances2[i]= LineChartView.Performance.LOSE;
                    break;
                default:
                    performances1[i]= LineChartView.Performance.LOSE;
                    break;
            }
        }
        myView.setPerformances(performances1,performances2);
    }
});

完整程式碼如下:

public class LineChartView extends View {
    private Context context;
    /*動畫插值器*/
    DecelerateInterpolator mDecelerateInterpolator = new DecelerateInterpolator();
    /*動畫重新整理的次數*/
    private int mDuration = 10;
    /*當前動畫進度值*/
    private int mCurrentTime = 0;
    private Performance[] mPerformance_1, mPerformance_2;
    /*兩條折線的顏色*/
    private int mLineColor1, mLineColor2;
    /*繪製表頭文字畫筆*/
    private Paint mPaintText = new Paint();
    /*繪製表格的畫筆*/
    private Paint mPaintLine = new Paint();
    /*第一條折線的畫筆*/
    private Paint mPaintLine1 =new Paint();
    /*第二條折線的畫筆*/
    private Paint mPaintLine2 =new Paint();
    /*座標點的小圓點畫筆*/
    private Paint mPointPaint = new Paint();
    private float mSmallDotRadius = 4;
    private TypedValue typedValue;
    private int mPaintClolor;
    /*Handler重新整理介面產生動畫效果*/
    private Handler mHandler = new Handler();
    private Runnable mAnimation = new Runnable() {
        @Override
        public void run() {
            if (mCurrentTime < mDuration) {
                mCurrentTime++;
                LineChartView.this.invalidate();
            }
        }
    };

    public LineChartView(Context context) {
        super(context);
        this.context=context;
        init();
    }

    public LineChartView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context=context;
        init();
    }

    public LineChartView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context=context;
        init();
    }

    public enum Performance {
        WIN(0),
        DRAW(1),
        LOSE(2);
        public int type;
        Performance(int type) {
            this.type = type;
        }
    }

    public void setPerformances(Performance[] performance1, Performance[] performance2) {
        if (performance1 == null) {
            performance1 = new Performance[0];
        }
        if (performance2 == null) {
            performance2 = new Performance[0];
        }
        mPerformance_1 = Arrays.copyOf(performance1, performance1.length > 8 ? 8 : performance1.length);
        mPerformance_2 = Arrays.copyOf(performance2, performance2.length > 8 ? 8 : performance2.length);
        if (isShown()) {
            mCurrentTime = 0;
            this.invalidate();
        }
    }

    /**
     * 設定折線1的顏色
     *
     * @param mLineColor1
     */
    public void setLineColor1(int mLineColor1) {
        this.mLineColor1 = mLineColor1;
    }

    /**
     * 設定折線2的顏色
     *
     * @param mLineColor2
     */
    public void setLineColor2(int mLineColor2) {
        this.mLineColor2 = mLineColor2;
    }

    private void init() {
        mLineColor1=Color.BLUE;
        mLineColor2 = Color.GREEN;
        typedValue=new TypedValue();
        context.getTheme().resolveAttribute(R.attr.title_bar,typedValue,true);
        mPaintClolor =getResources().getColor(typedValue.resourceId);

        final LineChartView.Performance[] performances1=new LineChartView.Performance[8];
        final LineChartView.Performance[] performances2=new LineChartView.Performance[8];
        final Random random=new Random();
        for(int i=0;i<performances1.length;i++){
            switch (random.nextInt(2016)%3){
                case 0:
                    performances1[i]= LineChartView.Performance.WIN;
                    break;
                case 1:
                    performances1[i]= LineChartView.Performance.DRAW;
                    break;
                case 2:
                    performances1[i]= LineChartView.Performance.LOSE;
                    break;
                default:
                    performances1[i]= LineChartView.Performance.LOSE;
                    break;
            }
            switch (random.nextInt(2016)%3){
                case 0:
                    performances2[i]= LineChartView.Performance.WIN;
                    break;
                case 1:
                    performances2[i]= LineChartView.Performance.DRAW;
                    break;
                case 2:
                    performances2[i]= LineChartView.Performance.LOSE;
                    break;
                default:
                    performances1[i]= LineChartView.Performance.LOSE;
                    break;
            }
        }
        setPerformances(performances1,performances2);
    }


    /**
     * @param canvas
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        /*獲取控制元件總寬高*/
        float totalWidth = getWidth();
        float totalHeight = getHeight();
        /*左邊取總寬度的八分之一繪製表格頭部*/
        float textWide = totalWidth / 8;
        /*左邊留一點空白*/
        float left_offset = 10;
        /*折線圖的總寬度等於控制元件的總寬度減去表頭和留白*/
        float chartWide = totalWidth - textWide - left_offset;
        /*一共三行,設定每一行的垂直座標*/
        float[] mLineYs = new float[]{totalHeight / 8, totalHeight / 2, totalHeight * 7 / 8};
        /*一共八列,設定每一列的水平座標*/
        float[] mLineXs = new float[]{
                textWide + left_offset + chartWide * 0 / 8,
                textWide + left_offset + chartWide * 1 / 8,
                textWide + left_offset + chartWide * 2 / 8,
                textWide + left_offset + chartWide * 3 / 8,
                textWide + left_offset + chartWide * 4 / 8,
                textWide + left_offset + chartWide * 5 / 8,
                textWide + left_offset + chartWide * 6 / 8,
                textWide + left_offset + chartWide * 7 / 8,
        };

        /*繪製表頭文字*/
        mPaintText.setStyle(Paint.Style.FILL);
        mPaintText.setColor(mPaintClolor);
        mPaintText.setAlpha(226);
        mPaintText.setTextSize(28);
        /*從中間開始繪製*/
        mPaintText.setTextAlign(Paint.Align.CENTER);
        /*測量文字大小,並計算偏移量*/
        Paint.FontMetrics fontMetrics = mPaintText.getFontMetrics();
        float textBaseLineOffset = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom;
        canvas.drawText("勝場", textWide / 2, mLineYs[0] + textBaseLineOffset, mPaintText);
        canvas.drawText("平局", textWide / 2, mLineYs[1] + textBaseLineOffset, mPaintText);
        canvas.drawText("負場", textWide / 2, mLineYs[2] + textBaseLineOffset, mPaintText);

        /*繪製表格畫筆設定*/
        mPaintLine.setStyle(Paint.Style.STROKE);
        mPaintLine.setAntiAlias(true);
        mPaintLine.setColor(mPaintClolor);
        mPaintLine.setAlpha(80);
        mPaintLine.setStrokeWidth(1);
        /*開始繪製表格*/
        /*繪製三條橫線*/
        for(int i=0;i<3;i++){
            canvas.drawLine(textWide, mLineYs[i], totalWidth, mLineYs[i], mPaintLine);
        }
        /*繪製八條豎線*/
        for(int i=0;i<8;i++){
            canvas.drawLine(mLineXs[i], 0, mLineXs[i], totalHeight, mPaintLine);
        }
        /*折線圖畫筆設定*/
        mPaintLine1.setStyle(Paint.Style.STROKE);
        /*設定透明度,取值範圍為0~255,數值越小越透明,0表示完全透明*/
        mPaintLine1.setAlpha(0);
        mPaintLine1.setAntiAlias(true);
        mPaintLine1.setColor(mLineColor1);
        mPaintLine1.setStrokeWidth(5);
        mPaintLine2.setStyle(Paint.Style.STROKE);
        /*設定透明度,取值範圍為0~255,數值越小越透明,0表示完全透明*/
        mPaintLine2.setAlpha(0);
        mPaintLine2.setAntiAlias(true);
        mPaintLine2.setColor(mLineColor2);
        mPaintLine2.setStrokeWidth(5);
        if (typedValue.resourceId==R.color.white){
            /*PorterDuff.Mode.SCREEN 上下層都顯示。*/
            mPaintLine2.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SCREEN));
            mPaintLine1.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SCREEN));
        }else {
            /*PorterDuff.Mode.DARKEN 上下層都顯示。變暗*/
            mPaintLine2.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DARKEN));
            mPaintLine1.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DARKEN));
        }
        /*畫節點處的小圓點的畫筆設定*/
        mPointPaint.setStyle(Paint.Style.STROKE);
        mPointPaint.setAntiAlias(true);
        mPointPaint.setColor(mPaintClolor);


        /*計算當前動畫進度對應的數值*/
        float animCurrentValue = mDecelerateInterpolator.getInterpolation(1.0f * mCurrentTime / mDuration);
        mPaintLine.setColor(mLineColor1);
        /*繪製第一條折線的路徑*/
        for (int i = 0; i < mPerformance_1.length - 1; i++) {
            /*折線圖的折線的畫筆設定粗一點*/
            mPaintLine.setStrokeWidth(5);
            /*計算當前節點的座標值*/
            float prePointX =mLineXs[i];
            float prePointY =mLineYs[2] - (mLineYs[2] - mLineYs[mPerformance_1[i].type]) * animCurrentValue;
            /*計算下一個節點的座標值*/
            float nextPointX=mLineXs[i + 1];
            float nextPointY=mLineYs[2] - (mLineYs[2] - mLineYs[mPerformance_1[i + 1].type]) * animCurrentValue;
            /*連線當前座標和下一個座標,繪製線段*/
            canvas.drawLine(prePointX, prePointY, nextPointX, nextPointY, mPaintLine1);
            /*當前節點座標處繪製小圓*/
            canvas.drawCircle(prePointX, prePointY, mSmallDotRadius, mPointPaint);
        }
        /*第一個折線圖的最後一個節點的座標*/
        float lastPointX=mLineXs[mPerformance_1.length - 1];
        float lastPointY= mLineYs[2] - (mLineYs[2] - mLineYs[mPerformance_1[mPerformance_1.length - 1].type]) * animCurrentValue;
        /*繪製最後一個節點的外圍小圓*/
        canvas.drawCircle(lastPointX,lastPointY ,mSmallDotRadius, mPointPaint);

        /*繪製第二條折線*/
        mPaintLine.setColor(mLineColor2);
        for (int i = 0; i < mPerformance_2.length - 1; i++) {
            /*折線圖的折線的畫筆設定粗一點*/
            mPaintLine.setStrokeWidth(5);
            /*計算當前節點的座標值*/
            float prePointX =mLineXs[i];
            float prePointY =mLineYs[2] - (mLineYs[2] - mLineYs[mPerformance_2[i].type]) * animCurrentValue;
            /*計算下一個節點的座標值*/
            float nextPointX=mLineXs[i + 1];
            float nextPointY=mLineYs[2] - (mLineYs[2] - mLineYs[mPerformance_2[i + 1].type]) * animCurrentValue;
            /*連線當前座標和下一個座標,繪製線段*/
            canvas.drawLine(prePointX, prePointY, nextPointX, nextPointY, mPaintLine2);
            /*當前節點座標處繪製小圓*/
            canvas.drawCircle(prePointX, prePointY, mSmallDotRadius, mPointPaint);
        }
         /*第一個折線圖的最後一個節點的座標*/
        lastPointX=mLineXs[mPerformance_2.length - 1];
        lastPointY= mLineYs[2] - (mLineYs[2] - mLineYs[mPerformance_2[mPerformance_2.length - 1].type]) * animCurrentValue;
        /*繪製最後一個節點的外圍小圓*/
        canvas.drawCircle(lastPointX,lastPointY ,mSmallDotRadius, mPointPaint);
        mHandler.postDelayed(mAnimation, 20);
    }
}

相關文章