
正文
Python Pygame (4) 图像的变换
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
Pygame中的transform模块可以使得你能够对图像(也就是Surface对象)做各种动作,列如左右上下翻转,按角度转动,放大缩小......,并返回Surface对象。这里列举了transform模块几个常用的方法及作用。

其实transform模块的这些方法使用的都是像素的变换,原理是通过一定的算法将图片进行像素位置修改。
大多数的方法在变换后难免造成一些精度上的损失(flip()方法不会)因此不建议对变换后的Surface对象进行再次变换。
例1
以之前小乌龟的例子,在这里使用smoothscale方法实现小乌龟的缩放:
# 放大、缩小小乌龟(=、-),空格键恢复原始尺寸
ratio = 1.0
oturtle = pygame.image.load("turtle.png")#oturtle用来保存最开始的图像
turtle = oturtle
oturtle_rect = oturtle.get_rect()
if event.key == K_EQUALS or event.key == K_MINUS or event.key == K_SPACE:
# 最大只能放大一倍,缩小50%
if event.key == K_EQUALS and ratio < 2:
ratio += 0.1
if event.key == K_MINUS and ratio > 0.5:
ratio -= 0.1
if event.key == K_SPACE:
ratio = 1.0 turtle = pygame.transform.smoothscale(oturtle, \
(int(oturtle_rect.width * ratio), \
int(oturtle_rect.height * ratio)))#使用整形
#相应修改龟头两个朝向的Surface对象,否则单一移动就会打回原形
l_head = turtle
r_head = pygame.transform.flip(turtle, True, False)
例2:
使用rotate()方法实现小乌龟的贴地行走。rotate(Surface,angle)方法的第二个参数angle是用来指定旋转的角度,是逆时针角度,我们原来的图像是面朝左的图像,因而可以通过每次90度的逆时针方向的旋转来实现。
speed = [5, 0]
turtle_right = pygame.transform.rotate(turtle, 90)
turtle_top = pygame.transform.rotate(turtle, 180)
turtle_left = pygame.transform.rotate(turtle, 270)
turtle_bottom = turtle
turtle = turtle_top#刚开始走顶部l_head = turtle
r_head = pygame.transform.flip(turtle, True, False)while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# 移动图像
position = position.move(speed) if position.right > width:
turtle = turtle_right
#变换后矩形的尺寸发生变化
position = turtle_rect = turtle.get_rect()
#矩形尺寸的改变导致位置也变化
position.left = width - turtle_rect.width
speed = [0, 5] if position.bottom > height:
turtle = turtle_bottom
position = turtle_rect = turtle.get_rect()
position.left = width - turtle_rect.width
position.top = height - turtle_rect.height
speed = [-5, 0] if position.left < 0:
turtle = turtle_left
position = turtle_rect = turtle.get_rect()
position.top = height - turtle_rect.height
speed = [0, -5] if position.top < 0:
turtle = turtle_top
position = turtle_rect = turtle.get_rect()
speed = [5, 0]








