Pygame 图像透明度混乱 [英] Pygame image transparency confusion

查看:27
本文介绍了Pygame 图像透明度混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里阅读了与此问题相关的前 20 篇文章,在 Google 上阅读了许多示例,尝试使用 .convert().convert_alpha(),尝试使用既没有尝试过 .png、.gif,也没有尝试过谷歌上排名前 5 位的不同图像.请有人帮我弄清楚如何使作品显示为透明背景.这是所有代码:

导入pygamepygame.init()打印(1")屏幕尺寸 = (600, 600)蓝色 = (100, 225, 225)屏幕 = pygame.display.set_mode(screen_size)pygame.display.set_caption(国际象棋")类 SpriteSheet:def __init__(self, 文件名):"加载纸张.""尝试:self.sheet = pygame.image.load(filename).convert.alpha()除了 pygame.error 为 e:打印(f无法加载精灵表图像:{文件名}")引发 SystemExit(e)def image_at(self, rectangle, colorkey = None):"从特定矩形加载特定图像.""# 从 x, y, x+offset, y+offset 加载图像.rect = pygame.Rect(矩形)图像 = pygame.Surface(rect.size)image.blit(self.sheet, (0, 0), rect)如果 colorkey 不是 None:如果颜色键 == -1:colorkey = image.get_at((0,0))image.set_colorkey(colorkey, pygame.RLEACCEL)返回图像def images_at(self, rects, colorkey = None):"加载一大堆图像并将它们作为列表返回.""返回 [self.image_at(rect, colorkey) for rect in rects]def load_strip(self, rect, image_count, colorkey = None):"""加载一整条图像,并将它们作为列表返回."""tups = [(rect[0]+rect[2]*x,rect[1],rect[2],rect[3])对于范围内的 x(image_count)]返回 self.images_at(tups, colorkey)打印(2")课堂游戏:def __init__(self):self.playing = 错误self.move = 0self.player_turn = 1self.quit = Falsedef退出(自我):self.quit = True打印(3")课件:def __init__(self):self.sprite = 无self.spacial = [0, 0, 0]self.temporal = [0, 0]self.position = [self.spatial, self.temporal]self.color = "";self.type = "打印(4")chess_image = SpriteSheet('ChessPiecesArray.png')颜色 = [白色",黑色"]类型 = [K"、Q"、B"、N"、R"、P"]rect_piece = (0, 0, 133, 133)打印(5")国际象棋类:def __init__(self):self.set = []def create_set(self):对于范围内的我(2):对于范围内的 j(6):this_piece = 片()this_piece.color = 颜色[i]this_piece.type = 类型[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)打印(6")国际象棋 = 游戏()set_one = ChessSet()set_one.create_set()打印(7")虽然不是 chess.quit:对于 pygame.event.get() 中的事件:如果 event.type == pygame.KEYDOWN:如果 event.key == pygame.K_q:国际象棋退出()screen.fill(蓝色)screen.blit(set_one.set[0].sprite, (10, 10))pygame.display.flip()

以下是我花时间尝试的一些图像:

这是我的代码错误消息的屏幕截图以及建议的更改

解决方案

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

您可以在创建新表面时启用其他功能.设置

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

class SpriteSheet:# [...]def image_at(self, rectangle, colorkey = None):"从特定矩形加载特定图像.""# 从 x, y, x+offset, y+offset 加载图像.rect = pygame.Rect(矩形)图像 = pygame.Surface(rect.size, pygame.SRCALPHA) # <----image.blit(self.sheet, (0, 0), rect)如果 colorkey 不是 None:如果颜色键 == -1:colorkey = image.get_at((0,0))image.set_colorkey(colorkey, pygame.RLEACCEL)返回图像

或者使用convert_alpha():

class SpriteSheet:# [...]def image_at(self, rectangle, colorkey = None):"从特定矩形加载特定图像.""# 从 x, y, x+offset, y+offset 加载图像.rect = pygame.Rect(矩形)图像 = pygame.Surface(rect.size).convert_alpha() # <----image.fill((0, 0, 0, 0)) # <---image.blit(self.sheet, (0, 0), rect)如果 colorkey 不是 None:如果颜色键 == -1:colorkey = image.get_at((0,0))image.set_colorkey(colorkey, pygame.RLEACCEL)返回图像

另见:


请注意,棋子也可以通过 Unicode 文本绘制.
请参阅使用 pygame 显示 unicode 符号

I have read the top 20 posts relating to this issue here, read many examples on Google, tried using .convert(), .convert_alpha(), tried with neither, tried with .png, .gif, tried with the top 5 different images on google. Please someone help me figure out how to make the pieces show with a transparent background. Here is ALL the code:

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()

Here are a few images I spent time trying:

EDIT: Here is the screenshot of my error message over my code with the suggested change

解决方案

If you copy a transparent Surface to another Surface the target Surface has to provide transparency respectively per pixel alpha.

You can enable additional functions when creating a new surface. Set the SRCALPHA flag to create a surface with an image format that includes a per-pixel alpha. The initial value of the pixels is (0, 0, 0, 0):

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

Use the following image

and adapt the method image_at of the class SpriteSheet. Use 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

Or use 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

See also:


Note that chess pieces can also be drawn through a Unicode text.
See Displaying unicode symbols using pygame

这篇关于Pygame 图像透明度混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆