pygame绘制图片的2种方法
1、绘制图片(方法一)
image = pygame.image.load("image.png")
screen.blit(image, (350, 250)) #图片+坐标
绘制图片的完整代码:
import pygame import sys pygame.init() screen = pygame.display.set_mode((800,600)) pygame.display.set_caption("标题") image_a = pygame.image.load("icon.png") running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.blit(image_a,(200,200)) pygame.display.flip() pygame.quit() sys.exit()2、若无图片,创建一个红色方块作为替代以便运行
image = pygame.Surface((100, 100)) # 创建一个宽高为100*100的对象
image.fill((255, 0, 0)) #填充红色
3、调用convert()绘制图片的步骤(方法二)
① 调用.convert()将像素格式转换为与显示表面兼容的格式
image = pygame.image.load("image.png").convert()
②get_rect()定位矩形
获取图片的矩形区域,用于定位:image_rect = image.get_rect()
居中显示图片:image_rect.center = (screen_width // 2, screen_height // 2)
③ 绘制图片
screen.blit(image, image_rect)
④ 绘画图片的完整代码
import pygame import sys import os # 初始化 Pygame pygame.init() # 设置窗口大小 screen_width = 800 screen_height = 600 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("Pygame 图片显示示例") # 尝试加载图片 image_path = "icon.png" if os.path.exists(image_path): try: # load() 返回一个 Surface 对象 # convert() 可以转换像素格式以加速 blit 操作 image = pygame.image.load(image_path).convert() except pygame.error as e: print(f"无法加载图片: {e}") # 创建备用表面 image = pygame.Surface((200, 200)) image.fill((0, 255, 0)) # 绿色方块 else: print(f"未找到 {image_path},使用备用彩色方块代替。") # 创建一个 200x200 的红色表面作为示例图片 image = pygame.Surface((200, 200)) image.fill((255, 0, 0)) # 获取图片的矩形区域,用于定位 image_rect = image.get_rect() # 将图片居中放置 image_rect.center = (screen_width // 2, screen_height // 2) # 游戏主循环 clock = pygame.time.Clock() running = True while running: # 1. 事件处理 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 2. 绘制背景 # 填充白色背景,清除上一帧的内容 screen.fill((255, 255, 255)) # 3. 绘制图片 # blit 方法将图像表面绘制到屏幕表面上 # 第二个参数可以是坐标元组 (x, y) 或者 Rect 对象 screen.blit(image, image_rect) # 4. 更新显示 # flip() 更新整个屏幕内容 pygame.display.flip() # 控制帧率为 60 FPS clock.tick(60) # 退出 Pygame pygame.quit() sys.exit()