kivy学习笔记—触控手势的识别

触控手势是触摸屏输入的一种较常见的方式,kivy库提供了触控手势的识别,有了它,就可以在程序中方便的应用手势来控制应用程序中的操作,提高程序的操控方便性。

from kivy.gesture import GestureDatabase
from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
from kivy.gesture import Gesture

# 构建需要响应的手势数据
ges_strs = {
    'left_to_right_line':'ds...', # 这里为什么必须很长的字符串 ??表示不解
    'right_to_left_line':'df...',# 这里为什么必须很长的字符串 ??表示不解
    'bottom_to_top_line':'eNq1m...'# 这里为什么必须很长的字符串 ??表示不解
}
gestures = GestureDatabase()

for name,ges_str in ges_strs.items():
    gesture = gestures.str_to_gesture(ges_str)
    gesture.name = name
    gestures.add_gesture(gesture)


class MyGesure(BoxLayout):
    def on_touch_down(self,touch): # 检测开始触摸动作
        touch.ud['gesture_path'] = [(touch.x,touch.y)] #记录动作坐标
        super().on_touch_down(touch)

    def on_touch_move(self,touch):# 检测开始划动动作
        touch.ud['gesture_path'].append((touch.x,touch.y))#记录划动坐标
        super().on_touch_move(touch)

    def on_touch_up(self,touch):#当手指抬起时
        # print(touch.ud['gesture_path'])
        if 'gesture_path' in touch.ud:
            gesture = Gesture()
            gesture.add_stroke(touch.ud['gesture_path'])
            gesture.normalize()
            match = gestures.find(gesture,minscore=0.9)
            if match:
                print('ha ha:',match[1].name)
        super().on_touch_up(touch)

class MygestureApp(App):
    def build(self):
        return MyGesure()

MygestureApp().run()

该代码运行后,在界面中使用手势时,控制台输出如下图:


更好的编程模式是将需要进行手势控制的部件建立一个类,其他类通过继承来使用。例如:

class MyGesWdgt(BoxLayout):
    def __init__(self, **kwargs):
        for name in gesture_strings:
        self.register_event_type('on_{}'.format(name))
        super(GestureBox, self).__init__(**kwargs)
    def on_left_to_right_line(self):
        pass
    def on_right_to_left_line(self):
        pass
    def on_bottom_to_top_line(self):
        pass

class MyGesWdgt_a(MyGesWdgt):
    pass

这样,只要修改前一段代码中的if match:为以下代码即可:

if match:
    self.dispatch('on_{}'.format(match[1].name))

在kv文件中也可以这样使用,就变得灵活多了:

on_right_to_left_line: app.root.action_method(root.location)
on_bottom_to_top_line: root.update_wdgt()
以上。

注:学习参考教材:OReilly Creating Apps in Kivy 2014

猜你喜欢

转载自blog.csdn.net/cloveses/article/details/80411730
今日推荐