Python 使用 pygame 旋转图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19316759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rotate image using pygame
提问by Pratik Singhal
I am new to pygame and want to write some code that simply rotates an image by 90 degrees every 10 seconds. My code looks like this:
我是 pygame 的新手,想编写一些代码,每 10 秒简单地将图像旋转 90 度。我的代码如下所示:
import pygame
import time
from pygame.locals import *
pygame.init()
display_surf = pygame.display.set_mode((1200, 1200))
image_surf = pygame.image.load("/home/tempuser/Pictures/desktop.png").convert()
imagerect = image_surf.get_rect()
display_surf.blit(image_surf,(640, 480))
pygame.display.flip()
start = time.time()
new = time.time()
while True:
end = time.time()
if end - start > 30:
break
elif end - new > 10:
print "rotating"
new = time.time()
pygame.transform.rotate(image_surf,90)
pygame.display.flip()
This code is not working ie the image is not rotating, although "rotating" is being printed in the terminal every 10 seconds. Can somebody tell me what I am doing wrong?
此代码不起作用,即图像不旋转,尽管每 10 秒在终端中打印“旋转”。有人可以告诉我我做错了什么吗?
采纳答案by sloth
pygame.transform.rotate
will not rotate the Surface
in place, but rather return a new, rotated Surface
. Even if it would alter the existing Surface
, you would have to blit it on the display surface again.
pygame.transform.rotate
不会Surface
原地旋转,而是返回一个新的、旋转的Surface
. 即使它会改变现有的Surface
,您也必须再次在显示表面上将其 blit 。
What you should do is to keep track of the angle in a variable, increase it by 90
every 10 seconds, and blit the new Surface
to the screen, e.g.
您应该做的是跟踪变量中的角度,90
每 10 秒增加一次,并将新的 blit 显示Surface
到屏幕上,例如
angle = 0
...
while True:
...
elif end - new > 10:
...
# increase angle
angle += 90
# ensure angle does not increase indefinitely
angle %= 360
# create a new, rotated Surface
surf = pygame.transform.rotate(image_surf, angle)
# and blit it to the screen
display_surf.blit(surf, (640, 480))
...