当使用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()
发布于 2014-11-26 19:13:42
您永远不会改变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
https://stackoverflow.com/questions/27157010
复制相似问题