Android 手勢(shì)相關(guān)(二)

Android 手勢(shì)相關(guān)(二)

本篇文章繼續(xù)記錄下android 手勢(shì)相關(guān)的內(nèi)容.

1: GestureOverlayView簡(jiǎn)介

GestureOverlayView是Android中的一個(gè)視圖組件,用于捕捉和處理手勢(shì)操作.

GestureOverlayView的主要用途:

  1. 手勢(shì)識(shí)別: 通過GestureOverlayView,保存一些手勢(shì),并堆用戶手勢(shì)操作進(jìn)行識(shí)別匹配.
  2. 手勢(shì)繪制: 我們還可以在GestureOverlayView繪制,并保存繪制路徑或者手勢(shì).
  3. 手勢(shì)交互: 我們可以監(jiān)聽手勢(shì)的開始,結(jié)束等事件.

本文主要介紹的是手勢(shì)識(shí)別這塊,實(shí)現(xiàn)的效果就是設(shè)置手勢(shì)的名稱, 保存手勢(shì), 繪制手勢(shì)判斷是否匹配.

2: 布局

界面布局主要有幾塊:

  1. EditText 用于設(shè)置手勢(shì)名稱
  2. btn1用于設(shè)置保存手勢(shì)動(dòng)作
  3. btn2用于設(shè)置匹配手勢(shì)動(dòng)作
  4. GestureOverlayView用于手勢(shì)繪制.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".GestureActivity">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:hint="請(qǐng)輸入保存手勢(shì)的名稱"
        android:id="@+id/edit_name"
        />
    <Button
        android:id="@+id/btn_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存手勢(shì)"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/edit_name"
        />

    <Button
        android:id="@+id/btn_compare"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="匹配手勢(shì)"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_save" />

    <android.gesture.GestureOverlayView
        android:id="@+id/gesture"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:background="#aaaaaa"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_compare" />
</androidx.constraintlayout.widget.ConstraintLayout>

GestureOverlayView在xml定義的屬性可以查看下attrs.xml.

<!-- GestureOverlayView specific attributes. These attributes are used to configure
     a GestureOverlayView from XML. -->
<declare-styleable name="GestureOverlayView">
    <!-- Width of the stroke used to draw the gesture. -->
    <attr name="gestureStrokeWidth" format="float" />
    <!-- Color used to draw a gesture. -->
    <attr name="gestureColor" format="color" />
    <!-- Color used to draw the user's strokes until we are sure it's a gesture. -->
    <attr name="uncertainGestureColor" format="color" />
    <!-- Time, in milliseconds, to wait before the gesture fades out after the user
         is done drawing it. -->
    <attr name="fadeOffset" format="integer" />
    <!-- Duration, in milliseconds, of the fade out effect after the user is done
         drawing a gesture. -->
    <attr name="fadeDuration" format="integer" />
    <!-- Defines the type of strokes that define a gesture. -->
    <attr name="gestureStrokeType">
        <!-- A gesture is made of only one stroke. -->
        <enum name="single" value="0" />
        <!-- A gesture is made of multiple strokes. -->
        <enum name="multiple" value="1" />
    </attr>
    <!-- Minimum length of a stroke before it is recognized as a gesture. -->
    <attr name="gestureStrokeLengthThreshold" format="float" />
    <!-- Squareness threshold of a stroke before it is recognized as a gesture. -->
    <attr name="gestureStrokeSquarenessThreshold" format="float" />
    <!-- Minimum curve angle a stroke must contain before it is recognized as a gesture. -->
    <attr name="gestureStrokeAngleThreshold" format="float" />
    <!-- Defines whether the overlay should intercept the motion events when a gesture
         is recognized. -->
    <attr name="eventsInterceptionEnabled" format="boolean" />
    <!-- Defines whether the gesture will automatically fade out after being recognized. -->
    <attr name="fadeEnabled" format="boolean" />
    <!-- Indicates whether horizontal (when the orientation is vertical) or vertical
         (when orientation is horizontal) strokes automatically define a gesture. -->
    <attr name="orientation" />
</declare-styleable>

這里我只用到了gestureStrokeWidth,gestureColor兩個(gè)屬性,并且是在代碼中設(shè)置的.

3: GestureLibrary對(duì)象

GestureLibrary 是android 中用于保存和管理手勢(shì)的類. 源碼很簡(jiǎn)單,具體的方法有興趣的都去試下

public abstract class GestureLibrary {
    protected final GestureStore mStore;

    protected GestureLibrary() {
        mStore = new GestureStore();
    }

    public abstract boolean save();

    public abstract boolean load();

    public boolean isReadOnly() {
        return false;
    }

    /** @hide */
    public Learner getLearner() {
        return mStore.getLearner();
    }

    public void setOrientationStyle(int style) {
        mStore.setOrientationStyle(style);
    }

    public int getOrientationStyle() {
        return mStore.getOrientationStyle();
    }

    public void setSequenceType(int type) {
        mStore.setSequenceType(type);
    }

    public int getSequenceType() {
        return mStore.getSequenceType();
    }

    public Set<String> getGestureEntries() {
        return mStore.getGestureEntries();
    }

    public ArrayList<Prediction> recognize(Gesture gesture) {
        return mStore.recognize(gesture);
    }

    public void addGesture(String entryName, Gesture gesture) {
        mStore.addGesture(entryName, gesture);
    }

    public void removeGesture(String entryName, Gesture gesture) {
        mStore.removeGesture(entryName, gesture);
    }

    public void removeEntry(String entryName) {
        mStore.removeEntry(entryName);
    }

    public ArrayList<Gesture> getGestures(String entryName) {
        return mStore.getGestures(entryName);
    }
}

創(chuàng)建對(duì)象:

gestureLibrary = GestureLibraries.fromFile("sdcard/gesture");

根據(jù)路徑創(chuàng)建gestureLibrary創(chuàng)建對(duì)象. 這里無需關(guān)注文件是否存在,save方法會(huì)有判斷:

public boolean save() {
    if (!mStore.hasChanged()) return true;

    final File file = mPath;

    final File parentFile = file.getParentFile();
    if (!parentFile.exists()) {
        if (!parentFile.mkdirs()) {
            return false;
        }
    }

    boolean result = false;
    try {
        //noinspection ResultOfMethodCallIgnored
        file.createNewFile();
        mStore.save(new FileOutputStream(file), true);
        result = true;
    } catch (FileNotFoundException e) {
        Log.d(LOG_TAG, "Could not save the gesture library in " + mPath, e);
    } catch (IOException e) {
        Log.d(LOG_TAG, "Could not save the gesture library in " + mPath, e);
    }

    return result;
}

由于是文件操作,權(quán)限不能忘記:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

4: GestureOverlayView

GestureOverlayView提供了三個(gè)接口實(shí)現(xiàn):

  1. addOnGestureListener(OnGestureListener listener)
  2. addOnGesturePerformedListener(OnGesturePerformedListener listener)
  3. addOnGesturingListener(OnGesturingListener listener)

這里我們使用addOnGesturePerformedListener,將手勢(shì)識(shí)別器與手勢(shì)監(jiān)聽器關(guān)聯(lián):

gestureOverlayView.setGestureColor(R.color.teal_200);
gestureOverlayView.setGestureStrokeWidth(5);
gestureOverlayView.addOnGesturePerformedListener(new GestureOverlayView.OnGesturePerformedListener() {
    @Override
    public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
          //處理手勢(shì)執(zhí)行 
    }
}

onGesturePerformed方法中我們做兩個(gè)操作:

  1. 保存手勢(shì)
  2. 判斷手勢(shì)匹配

保存手勢(shì)的操作:

根據(jù)onGesturePerformed回調(diào)的gesture,我們調(diào)用gestureLibrary.addGesture添加手勢(shì),并調(diào)用gestureLibrary.save()進(jìn)行保存.

gestureLibrary.addGesture(editText.getText().toString(), gesture);
if (gestureLibrary.save()) {
    Toast.makeText(GestureActivity.this, "保存手勢(shì)成功", Toast.LENGTH_LONG).show();
}else{
    Toast.makeText(GestureActivity.this, "保存手勢(shì)失敗", Toast.LENGTH_LONG).show();
}

判斷匹配:

調(diào)用recognize方法,傳入一個(gè)手勢(shì)參數(shù),返回與參數(shù)手勢(shì)最匹配的手勢(shì),

Prediction.score是用來表示手勢(shì)匹配的置信度或相似度的指標(biāo),

它是一個(gè)浮點(diǎn)數(shù)伸眶,范圍通常是0到10之間胸竞,表示匹配的程度.

ArrayList<Prediction> recognize = gestureLibrary.recognize(gesture);
Prediction prediction = recognize.get(0);
if (prediction.score >= 2) {
    Toast.makeText(GestureActivity.this, prediction.name + "匹配成功", Toast.LENGTH_SHORT).show();
} else {
    Toast.makeText(GestureActivity.this, prediction.name + "匹配失敗", Toast.LENGTH_SHORT).show();
}

完整的代碼如下:

public class GestureActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "GestureActivity";
    private GestureOverlayView gestureOverlayView;
    private Button btnSave, btnCompare;
    private int status = 0; // 1:保存手勢(shì) 2: 手勢(shì)比較
    private GestureLibrary gestureLibrary;
    private EditText editText;

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gesture);
        gestureOverlayView = findViewById(R.id.gesture);
        btnSave = findViewById(R.id.btn_save);
        btnCompare = findViewById(R.id.btn_compare);
        editText = findViewById(R.id.edit_name);
        gestureLibrary = GestureLibraries.fromFile("sdcard/gesture");
        btnSave.setOnClickListener(this);
        btnCompare.setOnClickListener(this);
        gestureOverlayView.setGestureColor(R.color.teal_200);
        gestureOverlayView.setGestureStrokeWidth(5);
        gestureOverlayView.addOnGesturePerformedListener(new GestureOverlayView.OnGesturePerformedListener() {
            @Override
            public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
                if (status == 1) {//保存手勢(shì)
                    if (gesture == null || gesture.getLength() <= 0) return;
                    if (TextUtils.isEmpty(editText.getText().toString())) {
                        Toast.makeText(GestureActivity.this, "請(qǐng)輸入手勢(shì)名稱", Toast.LENGTH_LONG).show();
                        return;
                    }
                    gestureLibrary.addGesture(editText.getText().toString(), gesture);
                    if (gestureLibrary.save()) {
                        Toast.makeText(GestureActivity.this, "保存手勢(shì)成功", Toast.LENGTH_LONG).show();
                    }else{
                        Toast.makeText(GestureActivity.this, "保存手勢(shì)失敗", Toast.LENGTH_LONG).show();
                    }
                } else if (status == 2) {//比較手勢(shì)
                    ArrayList<Prediction> recognize = gestureLibrary.recognize(gesture);
                    Prediction prediction = recognize.get(0);
                    if (prediction.score >= 2) {
                        Toast.makeText(GestureActivity.this, prediction.name + "匹配成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(GestureActivity.this, prediction.name + "匹配失敗", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_compare:
                status = 2;
                break;
            case R.id.btn_save:
                status = 1;
                break;
        }
    }
}

本文由博客一文多發(fā)平臺(tái) OpenWrite 發(fā)布!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末曙搬,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖渤早,帶你破解...
    沈念sama閱讀 211,348評(píng)論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異瘫俊,居然都是意外死亡鹊杖,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,122評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門扛芽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來骂蓖,“玉大人,你說我怎么就攤上這事川尖〉窍拢” “怎么了?”我有些...
    開封第一講書人閱讀 156,936評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵空厌,是天一觀的道長(zhǎng)庐船。 經(jīng)常有香客問我,道長(zhǎng)嘲更,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,427評(píng)論 1 283
  • 正文 為了忘掉前任揩瞪,我火速辦了婚禮赋朦,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己宠哄,他們只是感情好壹将,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,467評(píng)論 6 385
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著毛嫉,像睡著了一般诽俯。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上承粤,一...
    開封第一講書人閱讀 49,785評(píng)論 1 290
  • 那天暴区,我揣著相機(jī)與錄音,去河邊找鬼辛臊。 笑死仙粱,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的彻舰。 我是一名探鬼主播伐割,決...
    沈念sama閱讀 38,931評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼刃唤!你這毒婦竟也來了隔心?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,696評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤尚胞,失蹤者是張志新(化名)和其女友劉穎济炎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體辐真,經(jīng)...
    沈念sama閱讀 44,141評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡须尚,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,483評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了侍咱。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片耐床。...
    茶點(diǎn)故事閱讀 38,625評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖楔脯,靈堂內(nèi)的尸體忽然破棺而出撩轰,到底是詐尸還是另有隱情,我是刑警寧澤昧廷,帶...
    沈念sama閱讀 34,291評(píng)論 4 329
  • 正文 年R本政府宣布堪嫂,位于F島的核電站,受9級(jí)特大地震影響木柬,放射性物質(zhì)發(fā)生泄漏皆串。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,892評(píng)論 3 312
  • 文/蒙蒙 一眉枕、第九天 我趴在偏房一處隱蔽的房頂上張望恶复。 院中可真熱鬧怜森,春花似錦、人聲如沸谤牡。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,741評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽翅萤。三九已至恐疲,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間套么,已是汗流浹背培己。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評(píng)論 1 265
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留违诗,地道東北人漱凝。 一個(gè)月前我還...
    沈念sama閱讀 46,324評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像诸迟,于是被迫代替她去往敵國(guó)和親茸炒。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,492評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容