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

自定義 View 實作簡易折線圖:Canvas 繪製與逐筆動態刷新

編輯:關於 Android 開發

直說結論:折線圖在 Android 上不用急著找圖表庫,繼承 View、拿好 Paint、在 onDraw 裡把線段與圓點畫出來,再從外部推進資料觸發 invalidate 重繪,一個可用的圖表就成型了。下面是一個可直接跑的最小實作。

自定義 View

這支 CastView7 準備了四支畫筆分別負責座標軸、折線、資料點與文字,並在 onDraw 中依序畫出格線、刻度與折線。

public class CastView7 extends View {

    private Paint linePaint;    // 座標軸與格線
    private Paint zhexianPaint; // 折線
    private Paint dianPaint;    // 資料點
    private Paint textPaint;    // 文字

    private int x = 0;
    private int y = 0;

    // 用來存放每個點的 (x, y)
    private List<Map<String, Integer>> list =
            new ArrayList<Map<String, Integer>>();

    public final static String X = "x";
    public final static String Y = "y";
    public final static int DELL = 50;

    public CastView7(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();

        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        // 取得螢幕寬高
        x = wm.getDefaultDisplay().getWidth();
        y = wm.getDefaultDisplay().getHeight();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawLine(DELL, DELL, DELL, y - 250, linePaint); // 畫 Y 軸

        int county = (x - 250) / DELL;
        for (int i = 0; i < county / 2; i++) {
            // 循環畫出橫向的格線與刻度數字
            canvas.drawLine(DELL, (y - 250) - (DELL * i),
                    x - DELL, (y - 250) - (DELL * i), linePaint);
            canvas.drawText(i + "", 30, (y - 250) - (DELL * i), textPaint);
        }

        int countx = x / DELL;
        for (int i = 0; i < countx / 2; i++) {
            // 畫 X 軸刻度數字
            canvas.drawText(i + "", DELL + (100 * i), y - 220, textPaint);
        }

        for (int i = 0; i < list.size(); i++) {
            // 折線與拐点
            if (i > 0) {
                canvas.drawLine(
                        list.get(i - 1).get(X), list.get(i - 1).get(Y),
                        list.get(i).get(X), list.get(i).get(Y),
                        zhexianPaint);
            }
            canvas.drawCircle(list.get(i).get(X), list.get(i).get(Y),
                    5, dianPaint);
        }
    }

    private void init() {
        linePaint = new Paint();
        linePaint.setAntiAlias(true);
        linePaint.setColor(Color.BLACK);

        zhexianPaint = new Paint();
        zhexianPaint.setAntiAlias(true);
        zhexianPaint.setColor(Color.RED);

        dianPaint = new Paint();
        dianPaint.setAntiAlias(true);
        dianPaint.setStyle(Style.FILL);
        dianPaint.setColor(Color.BLUE);

        textPaint = new Paint();
        textPaint.setColor(Color.BLACK);
        textPaint.setAntiAlias(true);
    }

    // 留給 Activity 呼叫,加入一個資料點並重繪
    public void setList(int x, int y) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put(X, x);
        map.put(Y, y);
        list.add(map);
        invalidate();
    }
}

Activity:用子線程逐筆餵資料

這裡的示範用了一條背景線程,每秒產生一個隨機 Y 值,透過 Handler 丟給主線程更新 View。實務上把資料來源換成網路回傳或感測器即可,Handler 的轉發結構不變。

public class Activity7 extends Activity {

    private CastView7 cv7;
    private int x = 0;
    private int y = 0;

    private Handler h = new Handler() {
        public void handleMessage(android.os.Message msg) {
            cv7.setList(msg.arg1, msg.arg2); // 呼叫 setList 重繪 view
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity7);
        cv7 = (CastView7) findViewById(R.id.cv7);

        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        x = wm.getDefaultDisplay().getWidth();
        y = wm.getDefaultDisplay().getHeight();

        new Thread() {
            public void run() {
                int countx = x / 50;
                Log.i("zhangteng", countx / 2 + "");
                for (int i = 0; i < countx / 2; i++) {
                    int xx = 50 + (100 * i);
                    int yy = ((y - 250) - (50 * ((int) (Math.random() * 16))));

                    Message msg = new Message();
                    msg.what = 1;
                    msg.arg1 = xx;
                    msg.arg2 = yy;
                    h.sendMessage(msg);

                    try {
                        sleep(1000); // 一秒畫一個點
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
}

佈局檔

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.zhangteng.castomview7.CastView7
        android:id="@+id/cv7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

兩個容易忽略的細節

最後別忘了在 Manifest 中把 Activity 設為橫屏方向,否則座標計算基準會和預期不同。

另外提醒:範例用 Map 存每個點的座標,資料量大時開銷偏高,改成一個簡單的 Point 或 float 陣列會更省;而螢幕尺寸建議改用 onSizeChanged 或 DisplayMetrics 取得,getDefaultDisplay().getWidth() 在新版系統上已被標記為不建議使用。

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