在 KV 语言中 canvas 的中心放置一个形状(例如椭圆)

Placing a shape (e.g. ellipse) in the centre of the canvas in KV Language

我刚开始使用 Kivy,想在 canvas 的中心放置一个椭圆。目前我正在使用下面的代码,但是只有椭圆的左下角 'corner' 位于中心,因为位置似乎由每个形状的左下角决定。

如何在 KV 语言中 canvas 居中?提前谢谢你。

<Widget@BoxLayout>:
canvas.before:
    Color:
        rgb: [0.8, 0.8, 1]
    Rectangle:
        pos: self.pos
        size: self.size
canvas:
    Color:
        rgb: [0, 0, 0]
    Ellipse
        id: 'El'
        size: [100, 100]
        pos: [self.center_x, self.center_y]

是的,在 kivy 中 pos 总是指左下角。这是一个非常简单的解决方案:

from kivy.base import runTouchApp
from kivy.lang import Builder

runTouchApp(Builder.load_string("""
BoxLayout:
    canvas.before:
        Color:
            rgb: [0.8, 0.8, 1]
        Rectangle:
            pos: self.pos
            size: self.size
    canvas:
        Color:
            rgb: [0, 0, 0]
        Ellipse
            id: 'El'
            size: [100, 100]
            pos: [self.center_x - 100/2, self.center_y - 100/2]
            """))

我们只是从 x 中减去一半的宽度,从 y 中减去一半的高度。这是最简单的解决方案,但是可以通过使用 pos_hint FloatLayout 来完成,例如。