且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Pygame - 在精灵中加载图像

更新时间:2023-11-10 21:37:10

首先 加载 全局范围或单独模块中的图像并导入它.不要在__init__方法中加载,否则每次创建实例时都要从硬盘读取,很慢.

First load the image in the global scope or in a separate module and import it. Don't load it in the __init__ method, otherwise it has to be read from the hard disk every time you create an instance and that's slow.

现在您可以在类 (self.image = IMAGE) 中分配全局 IMAGE 并且所有实例都将引用此图像.

Now you can assign the global IMAGE in the class (self.image = IMAGE) and all instances will reference this 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)

如果你想为同一个类使用不同的图像,你可以在实例化时传递它们:

If you want to use different images for the same class, you can pass them during the instantiation:

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)

使用convertconvert_alpha(用于具有透明度的图像)方法来提高 blit 性能.


Use the convert or convert_alpha (for images with transparency) methods to improve the blit performance.

如果图像在子目录中(例如images"),则使用 os.path.join:

If the image is in a subdirectory (for example "images"), construct the path with os.path.join:

import os.path
import pygame as pg

IMAGE = pg.image.load(os.path.join('images', 'an_image.png')).convert_alpha()