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

Android 手勢密碼自訂控件實作解析

編輯:關於 Android 程式設計

看過不少手勢解鎖的教學影片,多半只講九宮格怎麼畫,卻沒把完整原始碼放出來,而且連線旋轉角度的算法也常有問題——直線畫到斜線時,圖元會出現奇怪的偏移。這裡把自己整理過的版本記錄下來,包含角度計算、路徑繪製與狀態回調。

一、整體思路

自訂 View 繼承而來,核心是三件事:

  1. 在 onMeasure/首次繪製時,依視圖實際寬高把九宮格九個點算出來,並處理橫竖屏的居中偏移。
  2. 在 onTouchEvent 中判斷手指是否壓到某個點、是否重複經過(交叉點),並維護已選點清單。
  3. 在 onDraw 中依每個點的狀態(正常/按下/錯誤)畫對應圖元,再用矩陣縮放旋轉把連線畫出來。

二、狀態與點的定義

public static class Point {
    public static int STATU_NORMAL = 0;   // 正常
    public static int STATU_PRESS  = 1;   // 按下
    public static int STATU_ERROR  = 2;   // 錯誤

    public float x;
    public float y;
    public int index;    // 密碼序號,1 ~ 9
    public int status;

    public Point() {}

    public Point(float x, float y) {
        this.x = x;
        this.y = y;
    }
}

三、初始化九宮格座標

先取一個正方形區域並算出 X/Y 偏移,讓九宮格在任意螢幕比例下都能居中。

private void initPoint() {
    mScreenWidth = getWidth();
    mScreenHeight = getHeight();

    if (mScreenWidth > mScreenHeight) {          // 橫屏
        offsetX = (mScreenWidth - mScreenHeight) / 2f;
        mScreenWidth = mScreenHeight;            // 用正方形做屏幕鎖
    } else {                                     // 豎屏
        offsetY = (mScreenHeight - mScreenWidth) / 2f;
        mScreenHeight = mScreenWidth;
    }

    mBitmapNormal    = BitmapFactory.decodeResource(getResources(), normal);
    mBitmapPress     = BitmapFactory.decodeResource(getResources(), press);
    mBitmapError     = BitmapFactory.decodeResource(getResources(), error);
    mBitmapLinePress = BitmapFactory.decodeResource(getResources(), linePress);
    mBitmapLineError = BitmapFactory.decodeResource(getResources(), lineError);

    float q = mScreenWidth / 4f, h = mScreenWidth / 2f, t = mScreenWidth - q;
    pointArray[0][0] = new Point(offsetX + q, offsetY + q);
    pointArray[0][1] = new Point(offsetX + h, offsetY + q);
    pointArray[0][2] = new Point(offsetX + t, offsetY + q);
    pointArray[1][0] = new Point(offsetX + q, offsetY + h);
    pointArray[1][1] = new Point(offsetX + h, offsetY + h);
    pointArray[1][2] = new Point(offsetX + t, offsetY + h);
    pointArray[2][0] = new Point(offsetX + q, offsetY + t);
    pointArray[2][1] = new Point(offsetX + h, offsetY + t);
    pointArray[2][2] = new Point(offsetX + t, offsetY + t);

    mRadioR = mBitmapNormal.getWidth() / 2;

    int index = 1;
    for (Point[] row : pointArray) {
        for (Point mp : row) {
            mp.index = index++;
        }
    }
    isFirst = true;
}

四、觸摸事件與交叉點判斷

@Override
public boolean onTouchEvent(MotionEvent event) {
    isOnTouch = true;
    isMovePoint = false;
    isFinished = false;

    int action = event.getAction();
    mCurrx = event.getX();
    mCurrY = event.getY();
    Point mPointIntersection = null;

    switch (action) {
        case MotionEvent.ACTION_DOWN:
            resetPointList();
            mPointIntersection = checkPoint();
            if (mPointIntersection != null) {
                isSelect = true;
            }
            break;
        case MotionEvent.ACTION_MOVE:
            if (isSelect) {
                mPointIntersection = checkPoint();
                if (mPointIntersection == null) {
                    isMovePoint = true;      // 手指在線上移動
                }
            }
            break;
        case MotionEvent.ACTION_UP:
            isFinished = true;
            isSelect = false;
            isOnTouch = false;
            break;
    }

    // 手勢尚未結束:若碰到新點,判斷是否重複經過
    if (!isFinished && isSelect && mPointIntersection != null) {
        if (crossPoint(mPointIntersection)) {
            isMovePoint = true;
        } else {
            mPointIntersection.status = Point.STATU_PRESS;
            pointList.add(mPointIntersection);
        }
    }

    // 手勢結束:連線數量不足 5 個點視為錯誤
    if (isFinished) {
        if (pointList.size() >= 2 && pointList.size() <= 4) {
            errorPoint();
            STATUS_PASSWORD = STATUS_PASSWORD_ERROR;
        } else if (pointList.size() <= 1) {
            resetPointList();                // 手勢不成立
        } else {
            STATUS_PASSWORD = STATUS_PASSWORD_OK;
        }
    }

    postInvalidate();

    if (isFinished && listener != null) {
        if (STATUS_PASSWORD == STATUS_PASSWORD_ERROR) {
            listener.onFail();
        } else if (STATUS_PASSWORD == STATUS_PASSWORD_OK) {
            listener.onSucceed(getPassword());
        }
    }
    return true;
}

/** 檢查手指位置與九個點是否有交集 */
private Point checkPoint() {
    for (int i = 0; i < pointArray.length; i++) {
        for (int j = 0; j < pointArray[i].length; j++) {
            Point point = pointArray[i][j];
            if (isIntersection(point, new Point(mCurrx, mCurrY), mRadioR)) {
                return point;
            }
        }
    }
    return null;
}

五、角度與連線繪製(關鍵的一段)

原來源碼在這裡算錯了。求兩點夾角時,正確公式是 angle = 180 / Math.PI * Math.acos(cos),也就是「角度 = 弧度 × 180 / π」;寫成 180 / (Math.PI / radian) 雖然代數上等價,但直覺上容易搞混,而 y < 0 的象限修正必須補回來,否則往上畫的線會翻反。

/** 求兩點之間的夾角(以 X 軸正向為 0 度,順時針為正) */
public static float getAngle(float px1, float py1, float px2, float py2) {
    float x = px2 - px1;
    float y = py2 - py1;
    if (x == 0 && y == 0) {
        return 0f;
    }
    double hypotenuse = Math.sqrt(x * x + y * y);
    double cos = x / hypotenuse;
    double radian = Math.acos(cos);
    float angle = (float) (radian * 180 / Math.PI);

    if (y < 0) {
        angle = 180 + (180 - angle);
    } else if (y == 0 && x < 0) {
        angle = 180;
    }
    return angle;
}

/** 依兩點距離縮放線條圖,再旋轉到正確角度貼上畫布 */
public void lineToCanvas(Canvas canvas, Point a, Point b) {
    float scaleX = (float) getDistance(a, b) / mBitmapLinePress.getWidth();
    float mAngle = getAngle(a.x, a.y, b.x, b.y);

    canvas.rotate(mAngle, a.x, a.y);
    Bitmap line = (a.status == Point.STATU_PRESS) ? mBitmapLinePress : mBitmapLineError;
    matrix.setScale(scaleX, 1);
    matrix.postTranslate(a.x - line.getWidth() / 2, a.y - line.getHeight() / 2);
    canvas.drawBitmap(line, matrix, mPaint);
    canvas.rotate(-mAngle, a.x, a.y);   // 還原旋轉,避免影響後續繪製
}

public static double getDistance(Point a, Point b) {
    return Math.sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}

public static boolean isIntersection(Point a, Point b, float r) {
    return getDistance(a, b) < r;
}

六、在頁面中使用

布局檔直接引入這個 View,Activity 或 Fragment 只要實作監聽介面即可。

Handler handler = new Handler();

/** 手勢未觸碰時,一秒後自動清空並重繪 */
public void updateLockPatern() {
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (!mLockPatern.isOnTouch) {
                mLockPatern.resetPointList();
                mLockPatern.postInvalidate();
            }
        }
    }, 1000);
}

@Override
public void onFail() {
    super.onFail();
    mLockToast.setText("手勢密碼至少需連接 5 個點");
}

@Override
public void onSucceed(String password) {
    super.onSucceed(password);
    if (BaseFragmentActivity.mLockPatern.getLock().equals(password)) {
        startActivity(new Intent(getActivity(), APIClass.mLockLogin));
        getActivity().finish();
    } else {
        mLockToast.setText("密碼錯誤,請重新繪製");
        mLockPatern.errorPoint();
        mLockPatern.postInvalidate();
        updateLockPatern();
    }
}

七、需要的資源檔

五張圖:nor.png(正常)、press.png(按下)、error.png(錯誤)、linepress.png(正常連線)、lineerror.png(錯誤連線)。線條圖只需一張單元格,靠矩陣橫向拉伸即可 reuse。

八、接入 App 時要考慮的四種情境

  • A. 啟動應用:若已設定手勢密碼,先要求驗證。
  • B. 建立手勢密碼:需二次確認,兩次一致才寫入。
  • C. 修改手勢密碼:先驗證舊密碼,再走建立流程。
  • D. 回前台時驗證:在 onResume 中記錄螢幕關閉/離開的時間間隔,超過門檻就彈出解鎖頁。

實務上我會用一個 BaseActivity 統一提供 registerReceiver,再讓 LockPaternActivity 繼承 FragmentActivity,內嵌四個 Fragment(引導、建立、確認、驗證),依 Intent 傳入的參數決定顯示哪一頁,結構會清楚很多。

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