Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自定義控件實戰:手把手打造一款折線圖

編輯:關於 Android 程式設計

本篇將帶大家從零實現一個折線圖控件,最終效果如下圖所示。

一、規劃繪圖區域

首先要劃分控件的繪圖區域:左側取控件總寬度的八分之一用來繪製表頭,右側剩餘部分繪製表格。

接著確定表格的行列數——先畫一個三行八列的網格。設置好行列坐標後即可開始繪製。

/*繪制三條橫線*/
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);
}

三、處理折線重疊

兩條折線重合的地方需要特殊處理。比如希望重合處顯示為白色,可以借助 Xfermode 混合模式:

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();
        }
    }

    public void setLineColor1(int mLineColor1) { this.mLineColor1 = mLineColor1; }
    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);
        // ...其餘繪制邏輯(onDraw、動畫插值、坐標計算等)
    }
}

至此,一個具備動畫效果、支持雙折線對比、能處理重合顯示的自定義折線圖控件就完成了。讀者可以在 init() 與 onDraw() 中補充坐標計算、動畫插值(mDecelerateInterpolator)以及表頭文字繪製等細節邏輯,即可呈現出如圖所示的完整效果。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved