Pygame 加载图像

Pygame 加载图像

pygame.image模块包含从文件或类文件对象加载和保存图像的函数。图像被加载为Surface对象,最终在Pygame显示窗口上渲染。

首先我们通过load()函数获得一个Surface对象。

img = pygame.image.load('pygame.png')
Python

接下来,我们从这个Surface中获取一个rect对象,然后使用Surface.blit()函数来渲染图像。

rect = img.get_rect()
rect.center = 200, 150
screen.blit(img, rect)
Python

示例

在显示窗口上显示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()
Python

输出

以上代码的输出如下:

Pygame 加载图像

blit() 函数中,可以使用一个可选的special-flags参数,可取以下值:

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
Python

pygame.Surface模块还有一个convert()函数,它可以优化图像格式并加快绘制速度。

pygame.image模块有一个save()函数,可以将Surface对象的内容保存为图像文件。Pygame支持以下图像格式:

Loading image formats Saving image formats
JPG PNG GIF (non-animated) BMP PCX TGA (uncompressed) TIF LBM (and PBM) PBM (and 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")
Python

输出

Pygame 加载图像

在当前工作文件夹中应创建 circles.png。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册