【问题标题】:Pygame image transparency confusion [duplicate]Pygame图像透明度混乱[重复]
【发布时间】:2021-02-18 14:33:52
【问题描述】:

我在这里阅读了与此问题相关的前 20 个帖子,在 Google 上阅读了许多示例,尝试使用 .convert().convert_alpha(),两者都不尝试,尝试使用 .png、.gif,尝试使用前 5 个不同的谷歌上的图片。请有人帮我弄清楚如何使这些作品以透明背景显示。 这是所有代码:

import pygame
pygame.init()
print("1")
screen_size = (600, 600)
blue = (100, 225, 225)
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("Chess")


class SpriteSheet:

    def __init__(self, filename):
        """Load the sheet."""
        try:
            self.sheet = pygame.image.load(filename).convert.alpha()
        except pygame.error as e:
            print(f"Unable to load spritesheet image: {filename}")
            raise SystemExit(e)


    def image_at(self, rectangle, colorkey = None):
        """Load a specific image from a specific rectangle."""
        # Loads image from x, y, x+offset, y+offset.
        rect = pygame.Rect(rectangle)
        image = pygame.Surface(rect.size)
        image.blit(self.sheet, (0, 0), rect)
        if colorkey is not None:
            if colorkey == -1:
                colorkey = image.get_at((0,0))
            image.set_colorkey(colorkey, pygame.RLEACCEL)
        return image

    def images_at(self, rects, colorkey = None):
        """Load a whole bunch of images and return them as a list."""
        return [self.image_at(rect, colorkey) for rect in rects]

    def load_strip(self, rect, image_count, colorkey = None):
        """Load a whole strip of images, and return them as a list."""
        tups = [(rect[0]+rect[2]*x, rect[1], rect[2], rect[3])
                for x in range(image_count)]
        return self.images_at(tups, colorkey)
print("2")

class Game:
    def __init__(self):
        self.playing = False
        self.move = 0
        self.player_turn = 1
        self.quit = False

    def quit(self):
        self.quit = True

print("3")
class Piece:
    def __init__(self):
        self.sprite = None
        self.spacial = [0, 0, 0]
        self.temporal = [0, 0]
        self.position = [self.spacial, self.temporal]
        self.color = ""
        self.type = ""

print("4")
chess_image = SpriteSheet('ChessPiecesArray.png')
colors = ["White", "Black"]
types = ["K", "Q", "B", "N", "R", "P"]
rect_piece = (0, 0, 133, 133)

print("5")


class ChessSet:
    def __init__(self):
        self.set = []

    def create_set(self):
        for i in range(2):
            for j in range(6):
                this_piece = Piece()
                this_piece.color = colors[i]
                this_piece.type = types[j]
                rect_set = (133*j, 133*i, 133*(j+1), 133*(i+1))
                this_piece.sprite = SpriteSheet.image_at(chess_image, rect_set)
                self.set.append(this_piece)

print("6")
chess = Game()
set_one = ChessSet()
set_one.create_set()

print("7")
while not chess.quit:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_q:
                chess.quit()
    screen.fill(blue)
    screen.blit(set_one.set[0].sprite, (10, 10))

    pygame.display.flip()

这是我花时间尝试的几张图片:

编辑:这是我的代码错误消息的屏幕截图,其中包含建议的更改

【问题讨论】:

  • 我通过透明工具运行了图像,但仍然无法正常工作,我尝试了多个图像和工具,但无法正常工作
  • 由于某种原因,我原来的图片链接没有显示,但现在显示了

标签: python image pygame alpha pygame-surface


【解决方案1】:

如果您将透明 Surface 复制到另一个 Surface,则目标 Surface 必须分别提供每个像素 alpha 的透明度。

您可以在创建新表面时启用其他功能。设置 SRCALPHA 标志以创建具有包含每像素 alpha 的图像格式的表面。像素的初始值为(0, 0, 0, 0):

my_surface = pygame.Surface((width, height), pygame.SRCALPHA)

使用下图

并修改SpriteSheet类的方法image_at。使用pygame.SRCALPHA

class SpriteSheet:
    # [...]

    def image_at(self, rectangle, colorkey = None):
        """Load a specific image from a specific rectangle."""
        # Loads image from x, y, x+offset, y+offset.
        rect = pygame.Rect(rectangle)
        
        image = pygame.Surface(rect.size, pygame.SRCALPHA) # <----
        
        image.blit(self.sheet, (0, 0), rect)
        if colorkey is not None:
            if colorkey == -1:
                colorkey = image.get_at((0,0))
            image.set_colorkey(colorkey, pygame.RLEACCEL)
        return image

或使用convert_alpha():

class SpriteSheet:
    # [...]

    def image_at(self, rectangle, colorkey = None):
        """Load a specific image from a specific rectangle."""
        # Loads image from x, y, x+offset, y+offset.
        rect = pygame.Rect(rectangle)
        
        image = pygame.Surface(rect.size).convert_alpha() # <----
        image.fill((0, 0, 0, 0))                          # <---
        
        image.blit(self.sheet, (0, 0), rect)
        if colorkey is not None:
            if colorkey == -1:
                colorkey = image.get_at((0,0))
            image.set_colorkey(colorkey, pygame.RLEACCEL)
        return image

另见:


请注意,棋子也可以通过 Unicode 文本绘制。
Displaying unicode symbols using pygame

【讨论】:

  • 我收到错误 AttributeError: module 'pygame' has no attribute 'SCRALPHA'
  • 请阅读What should I do when someone answers my question? 并考虑accept the answer,您认为对您最有帮助。
  • 问题仍未解决。即使导入库并加载建议的功能也不起作用。
  • @BrandonMartin 它对我来说很好用。请注意,您只能使用其中一张图片。只有 1 张图片是透明的。您的代码工作正常。您只需添加pygame.SRCALPHA。我认为你只是在开玩笑。
  • 它是最新版本,但您的解决方法有效!!!感谢您的耐心等待。
猜你喜欢
  • 1970-01-01
  • 2020-08-31
  • 2016-07-04
  • 2021-09-09
  • 1970-01-01
  • 2021-04-13
  • 2017-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多