当使用 Kivy 语言旋转和移动图像时,我无法理解 Kivy 在幕后所做的事情。
下面的代码应该在屏幕上以 45 度角绘制两个图像,然后每单击一次鼠标,就会进一步旋转它,然后将其移动到屏幕的右侧。
第一个图像是使用 Kivy 语言中定义的旋转绘制的,第二个图像是我尝试仅用 python 重做它的地方(以更好地理解 Kivy 实际在做什么),但我失败了,因为 Python 版本首先不当我增加 x 时,将图像向右移动,但看起来该图像的整个坐标系已旋转,因为它在屏幕上以 45 度角移动,其次,当我单击时,它不会旋转该图像。
我缺少什么,以及在 Python 中(不使用 Kivy 语言)需要做什么才能获得与第一个图像所使用的相同的行为?
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.image import Image
from kivy.graphics import Rotate
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty
from kivy.graphics.context_instructions import PopMatrix, PushMatrix
Builder.load_string('''
<TestKV>:
canvas.before:
PushMatrix
Rotate:
angle: self.angle
axis: (0, 0, 1)
origin: self.center
canvas.after:
PopMatrix
''')
class TestKV(Image):
angle = NumericProperty(0)
def __init__(self, x, **kwargs):
super(TestKV, self).__init__(**kwargs)
self.x = x
self.angle = 45
def on_touch_down(self, touch):
self.angle += 20
self.x += 10
class TestPY(Image):
angle = NumericProperty(0)
def __init__(self, x, **kwargs):
super(TestPY, self).__init__(**kwargs)
self.x = x
with self.canvas.before:
PushMatrix()
rot = Rotate()
rot.angle = 45
rot.origin = self.center
rot.axis = (0, 0, 1)
with self.canvas.after:
PopMatrix()
def on_touch_down(self, touch):
self.angle += 20
self.x += 10
class MainWidget(Widget):
#this is the main widget that contains the game.
def __init__(self, **kwargs):
super(MainWidget, self).__init__(**kwargs)
self.all_sprites = []
self.k = TestKV(source="myTestImage.bmp", x=10)
self.add_widget(self.k)
self.p = TestPY(source="myTestImage.bmp", x=200)
self.add_widget(self.p)
class TheApp(App):
def build(self):
parent = Widget()
app = MainWidget()
parent.add_widget(app)
return parent
if __name__ == '__main__':
TheApp().run()
Run Code Online (Sandbox Code Playgroud)
你永远不会改变指令的角度Rotate。您的小部件上有一个angle属性,但它没有链接到任何东西。尝试更新Rotate指令:
class TestPY(Image):
def __init__(self, **kwargs):
super(TestPY, self).__init__(**kwargs)
# self.x = x -- not necessary, x is a property and will be handled by super()
with self.canvas.before:
PushMatrix()
self.rot = Rotate()
self.rot.angle = 45
self.rot.origin = self.center
self.rot.axis = (0, 0, 1)
with self.canvas.after:
PopMatrix()
def on_touch_down(self, touch):
self.x += 10
self.rot.origin = self.center # center has changed; update here or bind instead
self.rot.angle += 20
Run Code Online (Sandbox Code Playgroud)