如何使用 Pygame 旋轉和縮放影像?
我們可以使用 Pygame 模組的 **pygame.transform.rotate** 和 **pygame.transform.scale** 函式分別旋轉和縮放影像。該函式用於將影像旋轉給定的角度(以度為單位)。該函式接受兩個引數 - 要旋轉的影像和旋轉角度。在這篇文章中,我們將分別使用 pygame.transform.rotate 和 pygame.transform.scale 函式來旋轉和縮放影像。
在 Pygame 中旋轉影像
演算法
在 Pygame 中旋轉影像 -
匯入 pygame 庫。
透過呼叫 **pygame.init()** 初始化 Pygame。
使用 **pygame.display.set_mode()** 設定螢幕大小。
使用 **pygame.image.load()** 載入要旋轉的影像。
使用 **pygame.transform.rotate()** 旋轉影像,並以度為單位指定旋轉角度。
使用 **screen.blit()** 在螢幕上繪製原始影像和旋轉後的影像。
呼叫 **pygame.display.flip()** 更新顯示。
使用監聽 pygame.QUIT 事件的 while 迴圈等待使用者關閉視窗。
使用 **pygame.quit()** 退出 Pygame。
語法
pygame.transform.rotate(Surface, angle)
這裡,**Surface** 是要旋轉的 Surface,**angle** 是要旋轉 Surface 的角度(以度為單位)。該函式返回一個包含旋轉後圖像的新 Surface。
示例
以下程式碼載入名為 python-logo.png 的影像,並使用 pygame.transform.rotate 函式將其旋轉 45 度,然後在螢幕上顯示原始影像和旋轉後的影像。blit 函式用於在螢幕上繪製圖像。
import sys import pygame pygame.init() screen = pygame.display.set_mode((400, 400)) # Load the image to rotate image = pygame.image.load('python-logo.png') # Rotate the image by 45 degrees rotated_image = pygame.transform.rotate(image, 45) # Display the original and rotated image on the screen screen.blit(image, (0, 0)) screen.blit(rotated_image, (200, 0)) pygame.display.flip() # Wait for the user to close the window while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit()
輸出
在 Pygame 中縮放影像
Pygame 提供了一個名為 pygame.transform.scale 的函式,該函式可以將影像縮放為給定大小。該函式接受兩個引數:要縮放的影像和影像的新大小。以下程式碼使用 **pygame.transform.scale** 函式將影像縮放為原始大小的兩倍。
演算法
在 Pygame 中縮放影像 -
匯入 pygame 庫。
透過呼叫 **pygame.init()** 初始化 Pygame。
使用 **pygame.display.set_mode()** 設定螢幕大小。
使用 **pygame.image.load()** 載入要縮放的影像。
使用 **pygame.transform.scale()** 縮放影像,並指定影像的新大小(作為 (width, height) 的元組)。
使用 **screen.blit()** 在螢幕上繪製原始影像和縮放後的影像。
呼叫 **pygame.display.flip()** 更新顯示。
使用監聽 pygame.QUIT 事件的 while 迴圈等待使用者關閉視窗。
使用 **pygame.quit()** 退出 Pygame。
語法
pygame.transform.scale(Surface, size)
這裡,**Surface** 是要縮放的 Surface,**size** 是表示 Surface 新大小的元組。該函式返回一個包含縮放後圖像的新 Surface。
示例
import pygame import sys pygame.init() screen = pygame.display.set_mode((700, 500)) # Load the image to scale image = pygame.image.load('python-logo.png') # Scale the image to 2x its original size scaled_image = pygame.transform.scale(image, (image.get_width() * 2, image.get_height() * 2)) # Display the original and scaled image on the screen screen.blit(image, (0, 0)) screen.blit(scaled_image, (200, 0)) pygame.display.flip() # Wait for the user to close the window while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit()
輸出
結論
在本文中,我們使用 **Pygame pygame.transform.rotate** 和 **pygame.transform.scale** 方法旋轉和縮放了影像。這些方法易於使用,並接受某些引數來旋轉和縮放影像。使用這些函式,您可以建立動態且視覺上吸引人的遊戲和應用程式。