首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python PyGame 繪圖並存檔:畫圓、填色、匯出 PNG 完整範例

     編輯:更多程式設計知識

PyGame 不僅能開發遊戲,也可作為離屏繪圖引擎。本例建立視窗、繪製藍色實心圓於白底,並匯出為 PNG 檔案。

完整程式碼


import pygame as pg

WHITE = (255, 255, 255)
BLUE  = (0, 0, 255)
WIDTH, HEIGHT = 300, 300

win = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption("PyGame draw circle and save")

win.fill(WHITE)
center = (WIDTH // 2, HEIGHT // 2)
radius = min(center)
pg.draw.circle(win, BLUE, center, radius, 0)  # width=0 表示填滿

fname = "circle_blue.png"
pg.image.save(win, fname)
print("file {} has been saved".format(fname))

pg.display.flip()

# 事件迴圈:按 ESC 或關閉視窗退出
while True:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            pg.quit()
            raise SystemExit
        elif event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:
            pg.quit()
            raise SystemExit

支援匯出格式

pg.image.save 支援 .bmp、.tga、.png、.jpg。

應用延伸

  • 程式化生成材質、圖示、QR Code。
  • 科學繪圖、數據視覺化匯出靜態圖片。
  • 自動化測試截圖比對基準圖產生。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved