如何在kivy python中制作不规则四边形按钮?

ahy6op9u  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(382)

我正在尝试用kivy制作一个android应用程序。它的用户界面以这两个名为“2d”和“3d”的按钮开始。请帮我用kivy创建一个不规则的四边形按钮。

nzk0hqpo

nzk0hqpo1#

你可以延长 Button 表现得像两个人一样 Buttons :

class MyButton(Button):
    my_state = StringProperty('')  # this will be 'b1' or 'b2', even when button is not down
    my_down_image = StringProperty('')
    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            rx, ry = self.to_widget(*touch.pos, relative=True)
            if ry > self.height/2.0:  # more complex geometry calculation required
                self.my_down_image = 'B2Down.png'
                self.my_state = 'b2'
            else:
                self.my_down_image = 'B1Down.png'
                self.my_state = 'b1'
        return super(MyButton, self).on_touch_down(touch)

这个 MyButton 类将两个属性添加到 Button 这个 my_statemy_down_image 财产。这个 my_state 财产将被没收 b1b2 取决于按下的子按钮(由 on_touch_down() ). 这个 my_down_image 属性设置为 B1Down.pngB2Down.png 描述了我们想要的 MyButton 看起来像 B1B2 压力很大。上述代码中的简单y坐标比较不起作用,必须更加复杂才能正确确定按下了哪个子按钮。这个 MyButton 可用于 kv 这样地:

MyButton:
    background_normal: 'B1andB2.png'
    on_press: app.do_butt_press(self)
    on_release: app.do_butt_release(self)

在哪里 app 方法如下所示:

def do_butt_press(self, button):
    print('on_butt_press', button.state, button.my_state)

def do_butt_release(self, button):
    print('on_butt_release', button.state, button.my_state)

而且 kv :

<-MyButton>:
    state_image: self.background_normal if self.state == 'normal' else self.my_down_image
    disabled_image: self.background_disabled_normal if self.state == 'normal' else self.background_disabled_down
    canvas:
        Color:
            rgba: self.background_color
        BorderImage:
            border: self.border
            pos: self.pos
            size: self.size
            source: self.disabled_image if self.disabled else self.state_image
        Color:
            rgba: 1, 1, 1, 1
        Rectangle:
            texture: self.texture
            size: self.texture_size
            pos: int(self.center_x - self.texture_size[0] / 2.), int(self.center_y - self.texture_size[1] / 2.)

以上 kv 规则主要只是默认规则的副本 Button 基维使用的规则。唯一的变化是使用 my_down_imagestate_image 定义。
对于本例 B1andB2.png 可以是:
B1Down.png :

B2Down.png :

相关问题