如何制作与kivy中的图片大小相同的小部件

时间:2020-06-26 19:18:11

标签: python kivy kivy-language

我想在应用程序的底部放置一个横幅,该横幅可以随着宽度的变化而缩放。但是,我无法使小部件的大小与图像的大小相对应,因此,我在横幅本身下面留了一些空白。该怎么办?

这是我的尝试:

FloatLayout:
    canvas.before:
        Color:
            rgb: utils.get_color_from_hex("#6ec4c1")
        Rectangle:
            size: self.size
            pos: self.pos
    GridLayout:
        cols: 3
        pos_hint: {"top": 0.95}
        size_hint: 1, 0.05
        ImageButton:
            source: "images/back_arrow.png"
            on_release: app.change_screen("home_screen")
        Image:
            source: "images/icon.png"
        Label:
            text: ""
    Image:
        id: banner
        keep_ratio: True
        allow_stretch: True
        size_hint: 1, None
        source: "images/banner.png"

此代码确实将图​​片放在底部!但理想情况下,我希望它以全屏宽度停留在底部,并以y缩放以适合它。这可能吗?

What I want and it only works for this specific aspect ratio of the screen

When I change the width of the screen I'd like it to scale in y to fit the screen instead it keeps y constant

1 个答案:

答案 0 :(得分:0)

默认情况下,任何size_hint中的Widget(1,1)。这意味着您的Image与其包含的FloatLayout的大小相同。因此,您可以为size_hint设置值,也可以设置size_hint: None, None然后为size提供值。另外,pos_hint: {"bottom": 1}不起作用,因为bottom不是pos_hint支持的密钥。如果您想在底部使用Image,请使用pos_hint: {'y':0},但是pos的默认值为(0,0),因此您甚至不需要pos_hint: {'y':0}

此外,如果您将size_hint设置为None而未提供相应的widthheight,则默认widthheight (即100)。

我想我终于得到了你想要的。您可以使用BoxLayout代替FloatLayoutBoxLayout将设置其子级的大小以适合其可用空间(请参见documentation)。因此,也许像这样的事情会起作用:

BoxLayout:
    orientation: 'vertical'
    canvas.before:
        Color:
            rgb: utils.get_color_from_hex("#6ec4c1")
        Rectangle:
            size: self.size
            pos: self.pos
    GridLayout:
        cols: 3
        pos_hint: {"top": 0.95}
        size_hint: 1, 0.05
        ImageButton:
            source: "images/back_arrow.png"
            on_release: app.change_screen("home_screen")
        Image:
            source: "images/icon.png"
        Label:
            text: ""
    Image:
        id: banner
        keep_ratio: True
        allow_stretch: True
        # size_hint: 1, None
        source: "images/banner.png"

请注意,在size_hint: 1, 0.05中设置GridLayout意味着BoxLayout的95%将被分配给横幅。