确定图形对象是否已被kivy触碰

2024-06-15 02:17:46 发布

您现在位置:Python中文网/ 问答频道 /正文

当我触按MyPaintWidget时,一个椭圆在它的canvas中被创建。 但是我还想检测用户何时接触到已经绘制的椭圆,这样我就可以执行其他指令,而不是再次绘制椭圆。 我看到self.collide_point只对Widget有效

有别的解决办法吗?你知道吗

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()

Tags: fromimportselfappdef绘制widgetclass
1条回答
网友
1楼 · 发布于 2024-06-15 02:17:46

您可以将椭圆的中心和半径存储在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()

相关问题 更多 >