First load全局范围或单独模块中的图像并将其导入。不要将其加载到__init__
方法,否则每次创建实例时都要从硬盘读取,速度很慢。
现在您可以分配全局IMAGE
在课堂里 (self.image = IMAGE
)并且所有实例都将引用该图像。
import pygame as pg
pg.init()
# The screen/display has to be initialized before you can load an image.
screen = pg.display.set_mode((640, 480))
IMAGE = pg.image.load('an_image.png').convert_alpha()
class Player(pg.sprite.Sprite):
def __init__(self, pos):
super().__init__()
self.image = IMAGE
self.rect = self.image.get_rect(center=pos)
如果你想对同一个类使用不同的图像,你可以在实例化过程中传递它们:
class Player(pg.sprite.Sprite):
def __init__(self, pos, image):
super().__init__()
self.image = image
self.rect = self.image.get_rect(center=pos)
player1 = Player((100, 300), IMAGE1)
player2 = Player((300, 300), IMAGE2)
Use the convert or convert_alpha
(对于具有透明度的图像)提高位块传输性能的方法。
如果图像位于子目录中(例如“images”),则使用以下命令构建路径os.path.join:
import os.path
import pygame as pg
IMAGE = pg.image.load(os.path.join('images', 'an_image.png')).convert_alpha()