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]
作者:王陸