Android 手勢相關(二)
本篇文章繼續記錄下android 手勢相關的內容.
1: GestureOverlayView簡介
GestureOverlayView是Android中的一個檢視元件,用於捕捉和處理手勢操作.
GestureOverlayView的主要用途:
- 手勢識別: 透過GestureOverlayView,儲存一些手勢,並堆使用者手勢操作進行識別匹配.
- 手勢繪製: 我們還可以在GestureOverlayView繪製,並儲存繪製路徑或者手勢.
- 手勢互動: 我們可以監聽手勢的開始,結束等事件.
本文主要介紹的是手勢識別這塊,實現的效果就是設定手勢的名稱, 儲存手勢, 繪製手勢判斷是否匹配.
2: 佈局
介面佈局主要有幾塊:
- EditText 用於設定手勢名稱
- btn1用於設定儲存手勢動作
- btn2用於設定匹配手勢動作
- GestureOverlayView用於手勢繪製.
<?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="請輸入儲存手勢的名稱"
android:id="@+id/edit_name"
/>
<Button
android:id="@+id/btn_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="儲存手勢"
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="匹配手勢"
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兩個屬性,並且是在程式碼中設定的.
3: GestureLibrary物件
GestureLibrary 是android 中用於儲存和管理手勢的類. 原始碼很簡單,具體的方法有興趣的都去試下
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);
}
}
建立物件:
gestureLibrary = GestureLibraries.fromFile("sdcard/gesture");
根據路徑建立gestureLibrary建立物件. 這裡無需關注檔案是否存在,save方法會有判斷:
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;
}
由於是檔案操作,許可權不能忘記:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
4: GestureOverlayView
GestureOverlayView提供了三個介面實現:
- addOnGestureListener(OnGestureListener listener)
- addOnGesturePerformedListener(OnGesturePerformedListener listener)
- addOnGesturingListener(OnGesturingListener listener)
這裡我們使用addOnGesturePerformedListener,將手勢識別器與手勢監聽器關聯:
gestureOverlayView.setGestureColor(R.color.teal_200);
gestureOverlayView.setGestureStrokeWidth(5);
gestureOverlayView.addOnGesturePerformedListener(new GestureOverlayView.OnGesturePerformedListener() {
@Override
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
//處理手勢執行
}
}
onGesturePerformed方法中我們做兩個操作:
- 儲存手勢
- 判斷手勢匹配
儲存手勢的操作:
根據onGesturePerformed回撥的gesture,我們呼叫gestureLibrary.addGesture新增手勢,並呼叫gestureLibrary.save()進行儲存.
gestureLibrary.addGesture(editText.getText().toString(), gesture);
if (gestureLibrary.save()) {
Toast.makeText(GestureActivity.this, "儲存手勢成功", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(GestureActivity.this, "儲存手勢失敗", Toast.LENGTH_LONG).show();
}
判斷匹配:
呼叫recognize方法,傳入一個手勢引數,返回與引數手勢最匹配的手勢,
Prediction.score是用來表示手勢匹配的置信度或相似度的指標,
它是一個浮點數,範圍通常是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:儲存手勢 2: 手勢比較
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) {//儲存手勢
if (gesture == null || gesture.getLength() <= 0) return;
if (TextUtils.isEmpty(editText.getText().toString())) {
Toast.makeText(GestureActivity.this, "請輸入手勢名稱", Toast.LENGTH_LONG).show();
return;
}
gestureLibrary.addGesture(editText.getText().toString(), gesture);
if (gestureLibrary.save()) {
Toast.makeText(GestureActivity.this, "儲存手勢成功", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(GestureActivity.this, "儲存手勢失敗", Toast.LENGTH_LONG).show();
}
} else if (status == 2) {//比較手勢
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;
}
}
}
本文由部落格一文多發平臺 OpenWrite 釋出!