
- Pygame 教程
- Pygame - 首頁
- Pygame - 概述
- Pygame - Hello World
- Pygame - 顯示模式
- Pygame - Locals 模組
- Pygame - 顏色物件
- Pygame - 事件物件
- Pygame - 鍵盤事件
- Pygame - 滑鼠事件
- Pygame - 繪製圖形
- Pygame - 載入影像
- Pygame - 在視窗中顯示文字
- Pygame - 移動影像
- Pygame - 使用數字鍵盤鍵移動
- Pygame - 使用滑鼠移動
- Pygame - 移動矩形物件
- Pygame - 使用文字作為按鈕
- Pygame - 影像變換
- Pygame - 音訊物件
- Pygame - 混音器通道
- Pygame - 播放音樂
- Pygame - 播放影片
- Pygame - 使用攝像頭模組
- Pygame - 載入游標
- Pygame - 訪問 CDROM
- Pygame - 精靈模組
- Pygame - PyOpenGL
- Pygame - 錯誤和異常
- Pygame 有用資源
- Pygame - 快速指南
- Pygame - 有用資源
- Pygame - 討論
Pygame - 載入影像
pygame.image 模組包含用於從檔案或類檔案物件載入和儲存影像的函式。影像被載入為 Surface 物件,最終渲染在 Pygame 顯示視窗上。
首先,我們透過 load() 函式獲取一個 Surface 物件。
img = pygame.image.load('pygame.png')
接下來,我們從這個 Surface 獲取一個 rect 物件,然後使用 Surface.blit() 函式渲染影像 -
rect = img.get_rect() rect.center = 200, 150 screen.blit(img, rect)
示例
在顯示視窗上顯示 Pygame 徽標的完整程式如下所示 -
import pygame pygame.init() screen = pygame.display.set_mode((400, 300)) img = pygame.image.load('pygame.png') done = False bg = (127,127,127) while not done: for event in pygame.event.get(): screen.fill(bg) rect = img.get_rect() rect.center = 200, 150 screen.blit(img, rect) if event.type == pygame.QUIT: done = True pygame.display.update()
輸出
以上程式碼的輸出如下所示 -

blit() 函式可以帶有一個可選的特殊標誌引數,該引數具有以下值之一 -
BLEND_RGBA_ADD BLEND_RGBA_SUB BLEND_RGBA_MULT BLEND_RGBA_MIN BLEND_RGBA_MAX BLEND_RGB_ADD BLEND_RGB_SUB BLEND_RGB_MULT BLEND_RGB_MIN BLEND_RGB_MAX
pygame.Surface 模組還有一個 convert() 函式,它可以最佳化影像格式並使繪製速度更快。
pygame.image 模組有一個 save() 函式,可以將 Surface 物件的內容儲存到影像檔案。Pygame 支援以下影像格式 -
載入影像格式 | 儲存影像格式 |
---|---|
JPG PNG GIF(非動畫) BMP PCX TGA(未壓縮) TIF LBM(和 PBM) PBM(和 PGM、PPM) XPM |
BMP TGA PNG JPEG |
示例
以下程式在顯示介面上繪製三個圓圈,並使用 image.save() 函式將其儲存為 circles.png 檔案。
import pygame pygame.init() screen = pygame.display.set_mode((400, 300)) done = False white=(255,255,255) red = (255,0,0) green = (0,255,0) blue = (0,0,255) bg = (127,127,127) while not done: for event in pygame.event.get(): screen.fill(bg) if event.type == pygame.QUIT: done = True pygame.draw.circle(screen, red, (200,150), 60,2) pygame.draw.circle(screen, green, (200,150), 80,2) pygame.draw.circle(screen, blue, (200,150), 100,2) pygame.display.update() pygame.image.save(screen, "circles.png")
輸出

circles.png 應該在當前工作資料夾中建立。
廣告