萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python PyGame 繪圖並保存圖片:從基本圖形到影像輸出

PyGame 繪圖基礎

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)。

copyright © 萬盛學電腦網 all rights reserved