在旋转图像和移动图像时使用Kivy语言时,我很难理解Kivy在幕后所做的事情。
下面是一个代码,它应该在屏幕上以45度角绘制两张图像,然后每按一次鼠标就可以旋转它,然后将它移到屏幕右侧。
使用Kivy语言中定义的旋转绘制第一个图像,其中第二个图像是我尝试仅在python中重做它(以更好地理解Kivy实际上在做什么),但是我失败了,因为当我增加x时,Python版本首先不会将图像向右移动,但看起来整个坐标系已经为该图像旋转,因为它在屏幕上以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()
答案 0 :(得分:4)
您永远不会更改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