Python實現手勢識別——Android GestureDetector

一、什麼是Android GestureDetector?

Android GestureDetector是一種功能強大的類,它可以識別各種手勢,例如單擊、雙擊、向上滑動、向下滑動、旋轉等。Android GestureDetector庫是在Android系統中可用的一個專用類,具有高度的可定製性和靈活性。

在Python中,使用Android Kivy庫可以輕鬆訪問Android GestureDetector庫,以實現手勢識別和識別響應。

二、如何使用Android GestureDetector?

要實現手勢識別,我們需要使用Android Kivy庫中的GestureListener類。該類繼承自Android GestureDetector類,提供了一個簡化的界面,以便我們可以更輕鬆地捕獲各種手勢。

以下是GestureListener類的基本用法示例:

from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.app import App
from kivy.gesture import Gesture, GestureDatabase, GestureNode
from kivy.uix.label import Label
from kivy.graphics import Color, Line

class GestureDraw(Widget):
    gesture = ObjectProperty(None)
    label = ObjectProperty(None)
    gesture_db = GestureDatabase() 

    def on_touch_down(self, touch):
        if not self.collide_point(*touch.pos):
            return
        self.gesture = Gesture()
        self.gesture.add_stroke([touch.pos])
        self.label.text = '[b]Started[/b]\n%s' % self.gesture.strk_len()
        return True

    def on_touch_move(self, touch):
        if not self.collide_point(*touch.pos):
            return
        self.gesture.add_stroke([touch.pos])
        self.label.text = '[b]Drawing[/b]\n%s' % self.gesture.strk_len()

    def on_touch_up(self,touch):
        if not self.collide_point(*touch.pos):
            return
        if not self.gesture.normalize():
            self.label.text = '[color=ff0000]Too short[/color]'
            self.gesture = None
            return True
        if len(self.gesture.nodes) < 2:
            self.label.text = '[color=ff0000]Too few\n nodes[/color]'
            self.gesture = None
            return True
        self.gesture_db.add_gesture(self.gesture.name, self.gesture)
        self.label.text = '[b]Saved Gesture[/b]'

    def on_double_tap(self):
        self.clear_widgets()
        self.__init__()
        self.add_widget(Label(text='+[b] Gesture\nLibrary[/b]\n%d Gestures' % len(self.gesture_db.gestures), font_size=30, markup = True, pos_hint = {'center_x':0.5, 'center_y':0.6}))
        for name in self.gesture_db.list_gestures():
            data = self.gesture_db.get_gesture(name)
            scale = min(self.width / data['width'], self.height / data['height'])
            trans_x = (self.width - data['width'] * scale) / 2.
            trans_y = (self.height - data['height'] * scale) / 2.
            for stroke in data['strokes']:
                points = [(x * scale + trans_x, self.height - (y * scale + trans_y)) for x, y in stroke]
                with self.canvas:
                    GestureDraw.color_255()
                    Line(points=points)

    @staticmethod
    def color_255(color=[1.0, 0.0, 0.0, 1]):
        Color(*[x * 255 for x in color])

在上述代碼中,我們定義了一個名為GestureDraw的小部件,該小部件可以捕獲手勢,並將其添加到手勢數據庫中。在屏幕上,我們可以向GestureDraw小部件繪製多個手勢,然後您可以雙擊來查看手勢庫,並將其轉換為相應的動作。

三、如何實現手勢響應?

要使用從手勢庫中檢索到的手勢來響應手勢,您可以使用GestureDetector類。以下是GestureDetector類的基本示例:

from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.app import App
from kivy.gesture import Gesture, GestureDatabase, GestureNode
from kivy.uix.label import Label
from kivy.graphics import Color, Line
from kivy.core.window import Window
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout

class GestureDraw(Widget):
    gesture = ObjectProperty(None)
    label = ObjectProperty(None)
    gesture_db = GestureDatabase() 

    def on_touch_down(self, touch):
        if not self.collide_point(*touch.pos):
            return
        self.gesture = Gesture()
        self.gesture.add_stroke([touch.pos])
        self.label.text = '[b]Started[/b]\n%s' % self.gesture.strk_len()
        return True

    def on_touch_move(self, touch):
        if not self.collide_point(*touch.pos):
            return
        self.gesture.add_stroke([touch.pos])
        self.label.text = '[b]Drawing[/b]\n%s' % self.gesture.strk_len()

    def on_touch_up(self,touch):
        if not self.collide_point(*touch.pos):
            return
        if not self.gesture.normalize():
            self.label.text = '[color=ff0000]Too short[/color]'
            self.gesture = None
            return True
        if len(self.gesture.nodes) < 2:
            self.label.text = '[color=ff0000]Too few\n nodes[/color]'
            self.gesture = None
            return True
        self.gesture_db.add_gesture(self.gesture.name, self.gesture)
        self.label.text = '[b]Saved Gesture[/b]'

    def on_double_tap(self):
        self.clear_widgets()
        self.__init__()
        self.add_widget(Label(text='+[b] Gesture\nLibrary[/b]\n%d Gestures' % len(self.gesture_db.gestures), font_size=30, markup = True, pos_hint = {'center_x':0.5, 'center_y':0.6}))
        for name in self.gesture_db.list_gestures():
            data = self.gesture_db.get_gesture(name)
            scale = min(self.width / data['width'], self.height / data['height'])
            trans_x = (self.width - data['width'] * scale) / 2.
            trans_y = (self.height - data['height'] * scale) / 2.
            for stroke in data['strokes']:
                points = [(x * scale + trans_x, self.height - (y * scale + trans_y)) for x, y in stroke]
                with self.canvas:
                    GestureDraw.color_255()
                    Line(points=points)

    @staticmethod
    def color_255(color=[1.0, 0.0, 0.0, 1]):
        Color(*[x * 255 for x in color])

class MyFlaotLayout(FloatLayout):

    def __init__(self, **kwargs):
        super(MyFlaotLayout, self).__init__(**kwargs)

        self.button1 = Button(text='按鈕1', size_hint=(None, None), pos_hint={'x':0.1,'y':0.1}, size=(100, 50))
        self.button1.bind(on_release=self.callback)
        self.add_widget(self.button1)

        self.button2 = Button(text='按鈕2', size_hint=(None, None), pos_hint={'x':0.9,'y':0.1}, size=(100, 50))
        self.button2.bind(on_release=self.callback)
        self.add_widget(self.button2)

    def callback(self, instance):
        if instance.text == '按鈕1':
            self.add_widget(Label(text='Button1 clicked!', pos_hint={'center_x':0.5, 'center_y':0.5}))

        if instance.text == '按鈕2':
            self.add_widget(Label(text='Button2 clicked!', pos_hint={'center_x':0.5, 'center_y':0.5}))

        for child in self.children:
            child.pos_hint = {'center_x': 0.5, 'center_y': 0.4}

class GestureApp(App):
    def build(self):
        layout = MyFlaotLayout()

        gd = GestureDraw() 
        layout.add_widget(gd) 
        gd.bind(on_double_tap=gd.on_double_tap) 

        label = Label(text='Click & Drag to draw gesture\nDouble-Click to Testing', markup=True,
                      size_hint_y=None, height=50, pos_hint={'center_x': 0.5, 'center_y': 0})
        gd.label = label 
        layout.add_widget(label)

        return layout

if __name__ == '__main__':
    GestureApp().run()

此示例中,我們創建了一個名為MyFlaotLayout的小部件,它包含兩個按鈕和一個可以響應手勢的GestureDraw小部件。當點擊按鈕時,會在屏幕上顯示一個文本標籤,告訴您已點擊哪個按鈕。如果您雙擊GestureDraw小部件,則會在控制台輸出」 Gesture Detected」消息。

四、總結

本文主要介紹了如何使用Python語言的Android GestureDetector庫實現手勢識別。首先,我們介紹了Android GestureDetector是什麼以及如何使用,並提供了一個使用GestureListener類的基本示例。然後,我們討論了如何使用從手勢庫中檢索到的手勢來響應手勢,並提供了一個使用GestureDetector類的基本示例。最後,在一個綜合示例中,我們演示了如何將GestureDraw小部件與其他小部件集成在同一布局內,並在響應手勢時進行相應的操作。

代碼示例:

請參考以上所有代碼部分。

原創文章,作者:KGPQ,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/146207.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
KGPQ的頭像KGPQ
上一篇 2024-10-29 18:58
下一篇 2024-10-29 18:58

相關推薦

  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29

發表回復

登錄後才能評論