Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 手勢識別實作:從建手勢庫到程式端匹配

Android 內建就有一套手勢識別機制,流程分成建庫與匹配兩段。

第一步:建立手勢庫

用 SDK 附的範例 GestureBuilder(位於 Android-sdk-windows\samples\android-8\GestureBuilder)。先把它匯入開發環境,編譯並部署到手机上,接著就能在上面畫手勢、存進庫中。產生的檔案會落在 SD 卡,預設名稱是 gestures。

第二步:在應用中載入並匹配

把 gestures 複製到專案的 res/raw 目錄,然後在版面配置裡放一塊可供繪製的畫布:

<android.gesture.GestureOverlayView
    android:id="@+id/gestures"
    android:layout_width="fill_parent"
    android:layout_height="0dip"
    android:layout_weight="1.0" />

接著註冊監聽、取得並載入手勢庫,最後把畫出的手勢丟進去比對:

gestureOverlayView.addOnGesturePerformedListener(...);

mLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures);
mLibrary.load();

List<Prediction> predictions = mLibrary.recognize(gesture);

recognize() 回傳的是清單而非單一答案,可能包含多個相似結果,匹配度最高的排在最前面。實務上通常取第一筆,並檢查它的 score 是否高於自訂門檻,太低就當作無法識別,而不是硬猜。

多筆畫手勢

多數手勢一筆就能完成,但有些需求需要多段筆畫,這時在配置裡加上:

android:gestureStrokeType="multiple"

字串資源

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">GestureTest</string>
    <string name="notrecognize">不能識別該手勢</string>
    <string name="noprediction">手勢識別率太低,請重新輸入</string>
</resources>

版面配置

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

    <android.gesture.GestureOverlayView
        android:id="@+id/myGestureView"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1.0" />

</LinearLayout>

兩種提示訊息正好對應兩種失敗:完全比不到候選是「不能識別」,比到了但分數太低則是「請重新輸入」。把這兩者分開,使用者才知道該換個手勢還是重畫一次。

Copyright © Linux教程網 All Rights Reserved