【问题标题】:finding out whether a graphics object has been touched kivy找出图形对象是否已被触摸 kivy
【发布时间】:2016-03-16 14:37:28
【问题描述】:

当我触及MyPaintWidget 时,会在其canvas 中创建一个椭圆。 但我也想检测用户何时触摸已经绘制的椭圆,以便我可以执行其他指令而不是再次绘制椭圆。 我看到self.collide_point 只适用于Widgets。

有其他解决方案吗?

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Color, Ellipse

class MyPaintWidget(Widget):
    def on_touch_down(self,touch):
        with self.canvas:
            Color(1,1,0)
            d=30
            Ellipse(pos=(touch.x-d/2,touch.y-d/2),size=(d,d))

class MyPaintApp(App):
    def build(self):
        return MyPaintWidget()

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

【问题讨论】:

    标签: android python user-interface kivy


    【解决方案1】:

    您可以将椭圆的中心和半径存储在 ListPropertyMyPaintWidget 中。在on_touch_down 中,您可以检查是否与任何椭圆发生碰撞,然后绘制另一个椭圆或执行其他操作。在下面的示例中,我添加了第二个半径来显示通用解决方案。

    from kivy.app import App
    from kivy.uix.widget import Widget
    from kivy.graphics import Color, Ellipse
    from kivy.properties import ListProperty
    
    class MyPaintWidget(Widget):
        ellipses = ListProperty()
        def touch_hits_ellipse(self, touch):
            return [ind for ind, e in enumerate(self.ellipses) if (touch.x - e[0] )**2.0/(e[2])**2.0 + (touch.y - e[1])**2/(e[3])**2 <= 1]
    
        def on_touch_down(self,touch):
            hit_ellipse = self.touch_hits_ellipse(touch)
            if len(hit_ellipse) == 0:
                with self.canvas:
                    Color(1,1,0)
                    d=30
                    d2=40
                    Ellipse(pos=(touch.x-d/2,touch.y-d2/2),size=(d, d2))
                self.ellipses.append((touch.x, touch.y, d/2.0, d2/2))
            else:
                print "We hit ellipse(s) {}".format(hit_ellipse)
    
    class MyPaintApp(App):
        def build(self):
            return MyPaintWidget()
    
    if __name__=='__main__':
        MyPaintApp().run()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-28
      • 2013-12-26
      • 2012-11-03
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多