編輯:關於 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 而來,基本就意味著畫面得由我們自己負責。我們一步一步來。
// 參數依次為:圓心 X、圓心 Y、半徑、畫筆
int radius = width / 2 - 10;
canvas.drawCircle(width / 2, height / 2, radius, circlePaint);
canvas.drawCircle(width / 2, height / 2, 15, dotPaint);
這部分要畫十二組「數字 + 短線」。按高中數學的算法去逐一計算每個數字和線段的座標當然可行,但運算量偏大。這裡換個思路:永遠只在十二點的位置作畫,靠旋轉畫布來定位。
要畫一點,就把畫布逆時針旋轉 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() 回到旋轉前的角度。這兩個方法通常成對出現,是很值得養成的習慣。
指針的思路和刻度一樣:先旋轉畫布,再畫線,最後恢復。時針走 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();
此時在佈局中加入:
<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 組合,就足以應付大量看似複雜的自繪需求。
Android Studio 多渠道打包實戰:一個模板適配所有應用市場
App 上線前經常會遇到一個瑣碎卻躲不掉的活兒:同一份代碼,要針對不同分發渠道打出多個 apk。 原因也很現實。國內安卓市場數量眾多,主流的就有應用寶、百度手機助手、豌豆
Android 新手必修:Activity 四大狀態與生命週期一次講透
前陣子一直在啃 Android 的基礎知識,興趣班的課程講得太抽象,聽到後面實在跟不上,乾脆自己找資料把 Activity 這個最核心的元件整理成一篇筆記,於是有了下面這
Android PullToRefresh 自訂下拉刷新動畫
PullToRefresh 是常見的下拉刷新開源元件。若預設動畫不符合產品需求,可以修改它的載入布局與刷新動畫,讓下拉刷新時呈現自訂效果。 自訂幀動畫 可以先建立 an
GridView 九宮格入門實例
今天剛好需要一個九宮格,順手做個簡單的 GridView demo 記錄一下。 第一步是版面:主檔放一個設為三欄的 GridView。 <?xml ver