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

自定義 View 實作筆記:從零打造一個會走動的時鐘

編輯:關於 Android 程式設計

很多人覺得自定義 View 是「高手」的象徵,其實不然。之所以感覺難,往往是因為它牽扯到太多陌生的類和 API,一時間把人搞暈了。這篇我們就從最基礎的繪圖 API 開始,一步一步走進自定義 View 的世界。

今天的目標很簡單:在螢幕上畫一個時鐘,並且讓它能自動走動。

一、準備工作

由於這種效果沒辦法靠繼承現有控件來湊出來,我們必須直接繼承 View 自己繪製。這篇先不談自定義屬性和 View 測量,View 尺寸、指針顏色等暫時都給固定值,重點放在繪圖 API 上。

需要的成員變數如下:

/** 繪製表盤的畫筆 */
private Paint circlePaint;
/** 繪製表盤數字 */
private Paint numPaint;
/** 繪製表心 */
private Paint dotPaint;
/** 時針 */
private Paint hourPaint;
/** 分針 */
private Paint minutePaint;
/** 秒針 */
private Paint secondPaint;
/** View 寬度,預設 256dp */
private int width;
/** View 高度,預設 256dp */
private int height;
/** 日曆類,用來取得當前時間 */
private Calendar calendar;
/** 各指針顏色 */
private int hourColor, minuteColor, secondColor;
/** 各指針寬度 */
private int hourWidth, minuteWidth, secondWidth;

二、關於構造方法

繼承 View 之後,系統要求我們實作它的構造方法,主要有四個:

public ClockView(Context context)

在 Java 代碼中 new 一個 View 時呼叫。

public ClockView(Context context, AttributeSet attrs)

在佈局文件中添加這個 View 時呼叫。

public ClockView(Context context, AttributeSet attrs, int defStyleAttr)

很多人看到第三個參數 defStyleAttr,以為在 XML 裡寫了 style 就會呼叫它,其實不然。系統不會主動呼叫這個構造方法(有興趣可以自己寫個 style,在裡面打條日誌驗證一下),需要我們自己顯式呼叫(可以在第二個構造方法裡呼叫)。顧名思義,defStyleAttr 是我們為自定義 View 指定的一個預設樣式,後續再詳細說明。另外還有一個帶 defStyleRes 的構造方法供高版本使用,這裡暫不展開。

一般來說,初始化動作(讀取 XML 屬性、建立畫筆等)都放在構造方法中,因為控件既可能由 Java 代碼建立,也可能由 XML 加載。寫法有兩種,先看直白的版本:

public ClockView(Context context) {
    super(context);
    initView();
}

public ClockView(Context context, AttributeSet attrs) {
    super(context, attrs);
    initView();
}

這樣寫沒問題,但思路顯得零散。參考 Android 自家控件的源碼,更推薦構造器鏈式的寫法:

// 代碼中創建控件時呼叫
public ClockView(Context context) {
    this(context, null);
}

// 佈局文件中創建 View 時呼叫
public ClockView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public ClockView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initView();
}

結果一樣,但層次清晰得多。

三、初始化成員

private void initView() {
    // 取得當前時間實例
    calendar = Calendar.getInstance();

    // 時鐘預設寬高
    width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 256,
            getResources().getDisplayMetrics());
    height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 256,
            getResources().getDisplayMetrics());

    // 初始化指針顏色
    hourColor = Color.RED;
    minuteColor = Color.GREEN;
    secondColor = Color.BLUE;

    // 初始化指針寬度
    hourWidth = 8;
    minuteWidth = 5;
    secondWidth = 2;

    circlePaint = new Paint();
    circlePaint.setAntiAlias(true);            // 去鋸齒
    circlePaint.setColor(Color.GREEN);
    circlePaint.setStyle(Paint.Style.STROKE);  // 描邊
    circlePaint.setStrokeWidth(6);

    dotPaint = new Paint();
    dotPaint.setAntiAlias(true);
    dotPaint.setColor(Color.RED);
    dotPaint.setStyle(Paint.Style.FILL);

    numPaint = new Paint();
    numPaint.setColor(Color.RED);
    numPaint.setAntiAlias(true);
    numPaint.setTextAlign(Paint.Align.CENTER); // 文本居中對齊

    hourPaint = new Paint();
    hourPaint.setColor(hourColor);
    hourPaint.setStyle(Paint.Style.FILL);
    hourPaint.setStrokeWidth(hourWidth);

    minutePaint = new Paint();
    minutePaint.setColor(minuteColor);
    minutePaint.setStyle(Paint.Style.FILL);
    minutePaint.setStrokeWidth(minuteWidth);

    secondPaint = new Paint();
    secondPaint.setColor(secondColor);
    secondPaint.setStyle(Paint.Style.FILL);
    secondPaint.setStrokeWidth(secondWidth);
}

先取一個當前時間實例,因為指針位置要依手機系統時間來算;接著初始化各指針的顏色、寬度以及對應的畫筆。這部分都很直觀,看註解即可。

四、繪製時鐘

準備工作完成後,真正的繪製放在 onDraw() 中。只要控件是直接繼承 View 而來,基本就意味著畫面得由我們自己負責。我們一步一步來。

1. 表盤

// 參數依次為:圓心 X、圓心 Y、半徑、畫筆
int radius = width / 2 - 10;
canvas.drawCircle(width / 2, height / 2, radius, circlePaint);

2. 表心

canvas.drawCircle(width / 2, height / 2, 15, dotPaint);

3. 刻度與數字

這部分要畫十二組「數字 + 短線」。按高中數學的算法去逐一計算每個數字和線段的座標當然可行,但運算量偏大。這裡換個思路:永遠只在十二點的位置作畫,靠旋轉畫布來定位。

要畫一點,就把畫布逆時針旋轉 30 度到十二點方向,畫完數字 1 和短線,再順時針轉回 30 度;要畫二點,就轉 60 度,以此類推。

for (int i = 1; i < 13; i++) {
    // 旋轉前保存畫布狀態
    canvas.save();
    canvas.rotate(i * 30, width / 2, height / 2);

    // 參數:起點 x、起點 y、終點 x、終點 y、畫筆
    canvas.drawLine(width / 2, height / 2 - radius,
                    width / 2, height / 2 - radius + 10, circlePaint);

    // 參數:文本、x 座標、基線 y、畫筆
    canvas.drawText(i + "", width / 2, height / 2 - radius + 22, numPaint);

    // 恢復畫布狀態
    canvas.restore();
}

每次旋轉前先呼叫 canvas.save() 保存狀態,畫完再用 canvas.restore() 回到旋轉前的角度。這兩個方法通常成對出現,是很值得養成的習慣。

4. 三根指針

指針的思路和刻度一樣:先旋轉畫布,再畫線,最後恢復。時針走 30 度一格,分針與秒針走 6 度一格。

int hour = calendar.get(Calendar.HOUR);
canvas.save();
canvas.rotate(hour * 30, width / 2, height / 2);
canvas.drawLine(width / 2, height / 2 + 20, width / 2, height / 2 - 90, hourPaint);
canvas.restore();

int minute = calendar.get(Calendar.MINUTE);
canvas.save();
canvas.rotate(minute * 6, width / 2, height / 2);
canvas.drawLine(width / 2, height / 2 + 30, width / 2, height / 2 - 110, minutePaint);
canvas.restore();

int second = calendar.get(Calendar.SECOND);
canvas.save();
canvas.rotate(second * 6, width / 2, height / 2);
canvas.drawLine(width / 2, height / 2 + 40, width / 2, height / 2 - 130, secondPaint);
canvas.restore();

5. 讓它動起來

此時在佈局中加入:

<org.mobiletrain.clockview.ClockView
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

運行一下,畫面上應該已經有一個時鐘,但它是靜止的。要讓它走動,只需在 onDraw() 的開頭重新取一次時間,結尾再排一次重繪:

// onDraw() 開頭
calendar = Calendar.getInstance();

// onDraw() 結尾,一秒後重繪
postInvalidateDelayed(1000);

五、完整程式碼

public class ClockView extends View {

    private Paint circlePaint, numPaint, dotPaint;
    private Paint hourPaint, minutePaint, secondPaint;
    private int width, height;
    private Calendar calendar;
    private int hourColor, minuteColor, secondColor;
    private int hourWidth, minuteWidth, secondWidth;

    // 代碼中創建控件時呼叫
    public ClockView(Context context) {
        this(context, null);
    }

    // 佈局文件中創建 View 時呼叫
    public ClockView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ClockView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView() {
        calendar = Calendar.getInstance();
        width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 256,
                getResources().getDisplayMetrics());
        height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 256,
                getResources().getDisplayMetrics());

        hourColor = Color.RED;
        minuteColor = Color.GREEN;
        secondColor = Color.BLUE;
        hourWidth = 8;
        minuteWidth = 5;
        secondWidth = 2;

        circlePaint = new Paint();
        circlePaint.setAntiAlias(true);
        circlePaint.setColor(Color.GREEN);
        circlePaint.setStyle(Paint.Style.STROKE);
        circlePaint.setStrokeWidth(6);

        dotPaint = new Paint();
        dotPaint.setAntiAlias(true);
        dotPaint.setColor(Color.RED);
        dotPaint.setStyle(Paint.Style.FILL);

        numPaint = new Paint();
        numPaint.setColor(Color.RED);
        numPaint.setAntiAlias(true);
        numPaint.setTextAlign(Paint.Align.CENTER);

        hourPaint = new Paint();
        hourPaint.setColor(hourColor);
        hourPaint.setStyle(Paint.Style.FILL);
        hourPaint.setStrokeWidth(hourWidth);

        minutePaint = new Paint();
        minutePaint.setColor(minuteColor);
        minutePaint.setStyle(Paint.Style.FILL);
        minutePaint.setStrokeWidth(minuteWidth);

        secondPaint = new Paint();
        secondPaint.setColor(secondColor);
        secondPaint.setStyle(Paint.Style.FILL);
        secondPaint.setStrokeWidth(secondWidth);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        calendar = Calendar.getInstance();

        int radius = width / 2 - 10;
        canvas.drawCircle(width / 2, height / 2, radius, circlePaint);
        canvas.drawCircle(width / 2, height / 2, 15, dotPaint);

        for (int i = 1; i < 13; i++) {
            canvas.save();
            canvas.rotate(i * 30, width / 2, height / 2);
            canvas.drawLine(width / 2, height / 2 - radius,
                            width / 2, height / 2 - radius + 10, circlePaint);
            canvas.drawText(i + "", width / 2, height / 2 - radius + 22, numPaint);
            canvas.restore();
        }

        int hour = calendar.get(Calendar.HOUR);
        canvas.save();
        canvas.rotate(hour * 30, width / 2, height / 2);
        canvas.drawLine(width / 2, height / 2 + 20, width / 2, height / 2 - 90, hourPaint);
        canvas.restore();

        int minute = calendar.get(Calendar.MINUTE);
        canvas.save();
        canvas.rotate(minute * 6, width / 2, height / 2);
        canvas.drawLine(width / 2, height / 2 + 30, width / 2, height / 2 - 110, minutePaint);
        canvas.restore();

        int second = calendar.get(Calendar.SECOND);
        canvas.save();
        canvas.rotate(second * 6, width / 2, height / 2);
        canvas.drawLine(width / 2, height / 2 + 40, width / 2, height / 2 - 130, secondPaint);
        canvas.restore();

        // 每隔 1 秒重繪,重繪會再次觸發 onDraw()
        postInvalidateDelayed(1000);
    }
}

到這裡,一個會自己走動的自定義時鐘就完成了。回顧一下整個過程,其實只用到 drawCircle、drawLine、drawText 三個 API,加上 canvas 的 save/rotate/restore 組合,就足以應付大量看似複雜的自繪需求。

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