You need to enable JavaScript to run this app. 如何在Kivy中保持原图尺寸不变实现背景图片重复平铺
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kivy中保持原图尺寸不变实现背景图片重复平铺

Kivy背景图不拉伸、自适应平铺/裁剪实现方案

查阅Kivy官方文档后未找到该问题的简单解决方案,因此做了示例复现问题。现有代码如下:

初始代码

backgroundtest.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

class Theotherpart(BoxLayout):
    pass

class BgApp(App):
    def build(self):
        return Theotherpart()

if __name__ == "__main__":
    BgApp().run()

bg.kv

<Theotherpart>
    canvas:
        Rectangle:
            size: self.size
            source: 'grass.jpg'

实际运行效果

运行后背景图会随窗口尺寸拉伸,不同窗口大小下效果如下:

大窗口小窗口
大窗口小窗口效果

预期效果

期望实现逻辑为:当背景图尺寸小于窗口时,在水平、垂直方向重复平铺背景图;当背景图尺寸大于窗口时,裁剪超出窗口的部分,效果如下:

大窗口预期效果小窗口预期效果
大窗口预期效果小窗口预期效果

之前尝试官方给出的重复纹理示例,调整窗口大小时图片仍然会变形;尝试添加keep_ratio: True参数也不生效,因为该参数仅对Image组件生效,此处是直接给Canvas的Rectangle设置source。

最终解决方案

  • 删除原有Theotherpart类
  • 替换为以下代码:

新backgroundtest.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty, ListProperty, StringProperty
from kivy.uix.widget import Widget

class Texture(Widget):
    texture = ObjectProperty(None)
    tex_size = ListProperty([375,375])
    tex_coords = ListProperty([1,1])
    texture_wrap = StringProperty('repeat')

class BgApp(App):
    def build(self):
        return Texture()

if __name__ == "__main__":
    BgApp().run()

新bg.kv

<Texture>
    BoxLayout:
        canvas:
            Rectangle:
                size: root.tex_size
                pos: root.tex_coords
                source: 'grass.jpg'

内容的提问来源于stack exchange,提问作者SSeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 20:36:08