首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Pygame中制作带有透明背景的图像?

如何在Pygame中制作带有透明背景的图像?
EN

Stack Overflow用户
提问于 2020-06-28 21:42:50
回答 2查看 147关注 0票数 1

我是编程新手,所以我买了Eric Matthes的"Python速成课程“这本书。最近,我决定在Pygame中重现精灵宝可梦战斗系统。到目前为止,我已经做了一个足够好的框架来启动战斗系统。我选择了精灵宝可梦Mew作为测试对象。我已经有了图片的透明背景,但pygame仍然显示了灰色和白色的方块。这是我的主代码文件:

代码语言:javascript
复制
from settings import Settings
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Pykemon Battle Simulator")
    pokemon = Mew(screen)
    mixer.music.load("battle_music.mp3")
    mixer.music.play(-1)

    while True:
        screen.fill(ai_settings.bg_color)
        pokemon.blitme()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
        pygame.display.flip()

run_game()

这是我的Mew设置文件:

代码语言:javascript
复制
import pygame

class Mew():
    def __init__(self, screen):
        """Initialize the Pokémon Mew and it's location """
        self.screen = screen

        #Load the pokemon and get it's rect.
        self.image = image = pygame.image.load("mew.jpg").convert_alpha()
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()
        #Start each new Pokemon at the bottom of the screen
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom
    
    def blitme(self):
        """Draw the pokemon's current location"""
        self.screen.blit(self.image, self.rect)

这个(https://imgur.com/a/OytJBUN)就是它的结果。我怎样才能使背景图片透明呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-06-28 21:48:50

问题出在图像格式上。JPEG图像没有alpha通道。您可以通过set_colorkey()设置透明色键,但结果不会令您满意,因为JPEG不是无损的。这意味着由于压缩,颜色将略有变化,并且颜色键将不能正常工作。例如白色:

代码语言:javascript
复制
self.image = image = pygame.image.load("mew.jpg")
self.image.set_colorkey((255, 255, 255))

或者使用set_colorkey()和像BMP这样的无损图像格式

代码语言:javascript
复制
self.image = image = pygame.image.load("mew.bmp")
self.image.set_colorkey((255, 255, 255))

或者使用PNG格式。例如:

代码语言:javascript
复制
image = pygame.image.load("mew.png").convert_alpha()
票数 3
EN

Stack Overflow用户

发布于 2020-06-28 22:41:02

在convert_alpha()函数中使用PNG:

代码语言:javascript
复制
image = pygame.image.load("image.png").convert_alpha()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62623341

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档