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

Android 自定義 View 開發詳解:以虛擬方向鍵為例

編輯:關於 Android 程式設計

做 Android 開發難免要自定義 View。很多人一聽到「自定義」就卻步,其實原理並不難,掌握幾個關鍵環節之後,實作起來相當直觀。本文以一個圓形虛擬方向鍵為例,走完整個流程。

基本套路

自定義 View 的核心就三步:繼承 View → 覆寫構造方法 → 實作 onDraw(),需要自己決定尺寸時再補上 onMeasure(),要處理觸碰就覆寫 onTouchEvent()。

本例的 VirtualKeyView 就是照這個套路來的:繼承 View,實作兩個構造方法與 onDraw(),並額外提供一組按鍵事件回呼介面給外部使用。

一、自定義 View 本體

package com.czm.customview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

public class VirtualKeyView extends View {

    private static final boolean bDebug = true;
    private static final String TAG = VirtualKeyView.class.getSimpleName();

    private Context mContext;

    private Bitmap bmpRound;        // 方向鍵底圖
    private Bitmap bmpRound_press;  // 方向鍵按下態
    private Bitmap bmpOk;           // 中央 OK 鍵
    private Bitmap bmpOk_press;     // OK 鍵按下態

    private int mWidth;             // 真實寬度
    private int widthBg = 584;      // 設計基準寬度
    private int widthMid = 220;     // 中心寬度
    private int cir_Centre_X = 292; // 圓心座標
    private int cir_Centre_Y = 292;
    private int bigRadius = 292;
    private int smallRadius = 110;
    private int smallCir_X = 182;
    private int smallCir_Y = 182;
    private float scale = 1.0f;

    private boolean isInit = false;
    private int inputPress = -1;    // 目前按下哪個鍵

    public VirtualKeyView(Context context) {
        super(context);
        mContext = context;
    }

    public VirtualKeyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    /**
     * 依實際寬度做等比縮放,讓同一套圖片能適配不同尺寸
     */
    private void initData() {
        mWidth = getWidth();
        scale = mWidth * 1.0f / widthBg;

        cir_Centre_X = (int) (cir_Centre_X * scale);
        cir_Centre_Y = (int) (cir_Centre_Y * scale);
        bigRadius = (int) (bigRadius * scale);
        smallRadius = (int) (smallRadius * scale);
        smallCir_X = (int) (smallCir_X * scale);
        smallCir_Y = (int) (smallCir_Y * scale);

        initView();
        isInit = true;
    }

    private void initView() {
        if (mWidth == widthBg) {
            // 剛好等於設計基準尺寸,直接載入不用縮放
            bmpRound = Utils.decodeCustomRes(mContext, R.drawable.controller_round);
            bmpRound_press = Utils.decodeCustomRes(mContext, R.drawable.controller_round_bg_pressed);
            bmpOk = Utils.decodeCustomRes(mContext, R.drawable.controller_ok);
            bmpOk_press = Utils.decodeCustomRes(mContext, R.drawable.controller_ok_pressed);
        } else {
            int mid = (int) (widthMid * scale);
            Bitmap bitmapTmp = Utils.decodeCustomRes(mContext, R.drawable.controller_round);
            bmpRound = Bitmap.createScaledBitmap(bitmapTmp, mWidth, mWidth, true);
            bitmapTmp.recycle();
            bitmapTmp = null;

            bitmapTmp = Utils.decodeCustomRes(mContext, R.drawable.controller_round_bg_pressed);
            bmpRound_press = Bitmap.createScaledBitmap(bitmapTmp, mWidth, mWidth, true);
            bitmapTmp.recycle();
            bitmapTmp = null;

            bitmapTmp = Utils.decodeCustomRes(mContext, R.drawable.controller_ok);
            bmpOk = Bitmap.createScaledBitmap(bitmapTmp, mid, mid, true);
            bitmapTmp.recycle();
            bitmapTmp = null;

            bitmapTmp = Utils.decodeCustomRes(mContext, R.drawable.controller_ok_pressed);
            bmpOk_press = Bitmap.createScaledBitmap(bitmapTmp, mid, mid, true);
            bitmapTmp.recycle();
            bitmapTmp = null;
        }
        System.gc();
    }

    /** 對外提供的資源釋放方法,Activity 銷毀時呼叫 */
    public void recycle() {
        if (bmpRound != null && !bmpRound.isRecycled()) {
            bmpRound.recycle();
            bmpRound = null;
        }
        if (bmpRound_press != null && !bmpRound_press.isRecycled()) {
            bmpRound_press.recycle();
            bmpRound_press = null;
        }
        if (bmpOk != null && !bmpOk.isRecycled()) {
            bmpOk.recycle();
            bmpOk = null;
        }
        if (bmpOk_press != null && !bmpOk_press.isRecycled()) {
            bmpOk_press.recycle();
            bmpOk_press = null;
        }
        System.gc();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (!isInit) {
            initData();
        }
        // 開啟抗鋸齒與位圖平滑
        canvas.setDrawFilter(new PaintFlagsDrawFilter(0,
                Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
        drawCir(canvas);
    }

    private void drawCir(Canvas canvas) {
        switch (inputPress) {
            case -1:    // 無按鍵
                canvas.drawBitmap(bmpRound, 0, 0, null);
                canvas.drawBitmap(bmpOk, smallCir_X, smallCir_Y, null);
                break;
            case KeyEvent.KEYCODE_DPAD_CENTER:   // 中央 OK 鍵
                canvas.drawBitmap(bmpRound, 0, 0, null);
                canvas.drawBitmap(bmpOk_press, smallCir_X, smallCir_Y, null);
                break;
            case KeyEvent.KEYCODE_DPAD_UP:       // 上
                drawBg(canvas, 180);
                canvas.drawBitmap(bmpOk, smallCir_X, smallCir_Y, null);
                break;
            case KeyEvent.KEYCODE_DPAD_DOWN:     // 下
                drawBg(canvas, 0);
                canvas.drawBitmap(bmpOk, smallCir_X, smallCir_Y, null);
                break;
            case KeyEvent.KEYCODE_DPAD_LEFT:     // 左
                drawBg(canvas, 90);
                canvas.drawBitmap(bmpOk, smallCir_X, smallCir_Y, null);
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:    // 右
                drawBg(canvas, 270);
                canvas.drawBitmap(bmpOk, smallCir_X, smallCir_Y, null);
                break;
            default:
                break;
        }
    }

    /** 同一張高亮底圖,靠旋轉呈現四個方向 */
    private void drawBg(Canvas canvas, int rotate) {
        canvas.save();
        canvas.rotate(rotate, cir_Centre_X, cir_Centre_Y);
        canvas.drawBitmap(bmpRound_press, 0, 0, null);
        canvas.restore();
    }
}

二、觸碰判定:用圓與角度判斷按了哪個鍵

這是整個元件最有意思的部分。判斷邏輯分兩層:

第一層,先算距離。把觸點座標平移到以圓心為原點,然後比較「距離平方」與「半徑平方」——用平方比較可以避開開根號的效能損耗。落在小圓內就是 OK 鍵,落在大圓外則忽略。

第二層,落在環狀區域時判斷方向。利用 y1 與 ±x1 的大小關係切出四個象限,對應上下左右。

public boolean onTouchEvent(MotionEvent event) {
    if (bDebug) {
        Log.d(TAG, "event.getAction() = " + event.getAction());
    }
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        int x1 = (int) (event.getX() - cir_Centre_X);
        int y1 = (int) (event.getY() - cir_Centre_Y);
        int x2 = x1 * x1;
        int y2 = y1 * y1;
        int bigRadius2 = bigRadius * bigRadius;
        int smallRadius2 = smallRadius * smallRadius;

        if (x2 + y2 < bigRadius2) {
            // 在圓形之內才有繼續計算的必要
            if (x2 + y2 < smallRadius2) {
                setOnKeyDown(KeyEvent.KEYCODE_DPAD_CENTER);
            } else if (y1 > x1) {
                if (y1 > -x1) {
                    setOnKeyDown(KeyEvent.KEYCODE_DPAD_DOWN);
                } else {
                    setOnKeyDown(KeyEvent.KEYCODE_DPAD_LEFT);
                }
            } else {
                if (y1 > -x1) {
                    setOnKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT);
                } else {
                    setOnKeyDown(KeyEvent.KEYCODE_DPAD_UP);
                }
            }
        }
        postInvalidate();
        return true;
    }

    if (event.getAction() == MotionEvent.ACTION_UP) {
        int x1 = (int) (event.getX() - cir_Centre_X);
        int y1 = (int) (event.getY() - cir_Centre_Y);
        int x2 = x1 * x1;
        int y2 = y1 * y1;
        int bigRadius2 = bigRadius * bigRadius;
        int smallRadius2 = smallRadius * smallRadius;

        if (x2 + y2 < bigRadius2) {
            if (x2 + y2 < smallRadius2) {
                setOnKeyUp(KeyEvent.KEYCODE_DPAD_CENTER);
            } else if (y1 > x1) {
                if (y1 > -x1) {
                    setOnKeyUp(KeyEvent.KEYCODE_DPAD_DOWN);
                } else {
                    setOnKeyUp(KeyEvent.KEYCODE_DPAD_LEFT);
                }
            } else {
                if (y1 > -x1) {
                    setOnKeyUp(KeyEvent.KEYCODE_DPAD_RIGHT);
                } else {
                    setOnKeyUp(KeyEvent.KEYCODE_DPAD_UP);
                }
            }
        }
        postInvalidate();
    }
    return true;
}

private void setOnKeyDown(int keyCode) {
    inputPress = keyCode;
    if (myIntputCallBack != null) {
        myIntputCallBack.intputDown(keyCode);
    }
}

private void setOnKeyUp(int keyCode) {
    inputPress = -1;
    if (myIntputCallBack != null) {
        myIntputCallBack.intputUp(keyCode);
    }
}

/******************* 輸入回呼函數 ********************/

private IntputCallBack myIntputCallBack = null;

public interface IntputCallBack {
    void intputDown(int keyCode);
    void intputUp(int keyCode);
}

public void setOnInputCallBack(IntputCallBack myIntputCallBack) {
    this.myIntputCallBack = myIntputCallBack;
}

三、在版面檔中使用

自定義 View 在 XML 裡的用法和 <TextView> 完全一樣,只要寫上完整類別路徑:

<com.czm.customview.VirtualKeyView
    android:id="@+id/virtualKeyView"
    android:layout_marginTop="20dp"
    android:layout_width="250dp"
    android:layout_height="250dp"
    android:layout_centerHorizontal="true" />

四、在 Activity 中使用

Java 端也和一般 View 無異:findViewById 取得實例、設定回呼監聽。

package com.czm.customview;

import com.czm.customview.VirtualKeyView.IntputCallBack;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.widget.Toast;

public class MainActivity extends Activity {

    private VirtualKeyView virtualKeyView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        virtualKeyView = (VirtualKeyView) findViewById(R.id.virtualKeyView);
        virtualKeyView.setOnInputCallBack(new IntputCallBack() {

            @Override
            public void intputUp(int keyCode) {
            }

            @Override
            public void intputDown(int keyCode) {
                if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                    showToast("您按了 上 鍵");
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                    showToast("您按了 下 鍵");
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
                    showToast("您按了 左 鍵");
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
                    showToast("您按了 右 鍵");
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
                    showToast("您按了 OK 鍵");
                }
            }
        });
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        virtualKeyView.recycle();
    }
}

五、圖片載入工具

直接從 raw resource 解碼,不做額外縮放,保留原始尺寸給後續 scaling 使用:

package com.czm.customview;

import java.io.InputStream;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Utils {

    public static Bitmap decodeCustomRes(Context c, int res) {
        InputStream is = c.getResources().openRawResource(res);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inSampleSize = 1; // 原尺寸載入,不縮放
        return BitmapFactory.decodeStream(is, null, options);
    }
}

幾個值得學的設計細節

基準尺寸 + 等比縮放。以 584px 為設計基準,實際寬度不同時用 scale 折算所有座標與半徑,這比為每種螢幕準備一套圖片省事得多。

一張圖乘四個角度。方向鍵的高亮態只準備一張,靠 canvas.rotate() 搭配 save/restore 轉出四個方向,資源用量減到四分之一。

平方比較代替開根號。觸碰判定中完全不呼叫 Math.sqrt(),在需要即時回應的場合是實際有效的優化。

顯式 recycle。自定義 View 持有 Bitmap 時,記得對外提供 recycle() 並在 onDestroy() 呼叫,避免圖片記憶體被長期佔用。

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