pygame 不僅用於遊戲開發,其繪圖模組 pygame.draw 可離屏渲染並保存為圖片檔,適合程式化生成圖表、圖示、驗證碼等。
import pygame as pg
# 顏色常數 (R, G, B)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
WIDTH, HEIGHT = 300, 300
# 初始化
pg.init()
# 建立離屏 Surface (不顯示視窗也可繪圖)
surface = pg.Surface((WIDTH, HEIGHT))
surface.fill(WHITE)
# 繪製圓形
center = (WIDTH // 2, HEIGHT // 2)
radius = min(center)
pg.draw.circle(surface, BLUE, center, radius, 0) # width=0 表示填滿
# 保存圖片
fname = "circle_blue.png"
pg.image.save(surface, fname)
print(f"已保存: {fname}")
pg.quit()
import pygame as pg
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
WIDTH, HEIGHT = 300, 300
pg.init()
win = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption("PyGame Draw & Save")
win.fill(WHITE)
center = (WIDTH//2, HEIGHT//2)
radius = min(center)
pg.draw.circle(win, BLUE, center, radius, 0)
fname = "circle_blue.png"
pg.image.save(win, fname)
print(f"檔案已保存: {fname}")
pg.display.flip()
# 事件迴圈:支援關閉視窗、ESC 離開
running = True
while running:
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
elif event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:
running = False
pg.quit()
| 函式 | 用途 | 關鍵參數 |
|---|---|---|
pg.draw.rect(surf, color, rect, width=0) | 矩形 | rect=(x,y,w,h) |
pg.draw.circle(surf, color, center, radius, width=0) | 圓形 | width=0 填滿 |
pg.draw.ellipse(surf, color, rect, width=0) | 橢圓 | 外接矩形 |
pg.draw.line(surf, color, start, end, width=1) | 直線 | 寬度 |
pg.draw.lines(surf, color, closed, points, width=1) | 多段線 | closed 是否閉合 |
pg.draw.polygon(surf, color, points, width=0) | 多邊形 | 頂點列表 |
pg.draw.arc(surf, color, rect, start_angle, stop_angle, width=1) | 圓弧 | 弧度制 |
def draw_labeled_circle():
pg.init()
surf = pg.Surface((400, 300))
surf.fill(WHITE)
# 繪製圖形
pg.draw.circle(surf, BLUE, (200, 150), 80)
pg.draw.rect(surf, (255,0,0), (150, 250, 100, 30))
# 文字
font = pg.font.SysFont('arial', 24)
text = font.render("Hello PyGame", True, (0,0,0))
text_rect = text.get_rect(center=(200, 150))
surf.blit(text, text_rect)
pg.image.save(surf, "labeled_circle.png")
pg.quit()
.bmp:無壓縮、相容性最好.png:無損壓縮、支援透明度 (需 Surface 有 alpha 通道).jpg / .jpeg:有損壓縮、相片適合.tga:遊戲開發常用透明背景需建立 pg.Surface((w,h), pg.SRCALPHA)。