如何转换图像的背景颜色以匹配 Pygame 窗口的颜色?
Posted
技术标签:
【中文标题】如何转换图像的背景颜色以匹配 Pygame 窗口的颜色?【英文标题】:How to convert the background color of image to match the color of Pygame window? 【发布时间】:2021-01-06 14:45:03 【问题描述】:我需要做的是将图像背景的颜色与 Pygame 窗口的颜色相匹配。 但是图像和pygame窗口的背景不匹配。它看起来像这样
ship.py
import pygame
class Ship:
""" A class to manage the ship. """
def __init__(self, ai_game):
""" Initialize the ship and the starting position. """
self.screen = ai_game.screen
self.screen_rect = ai_game.screen.get_rect()
# Load the ship image and get its rect.
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
# Start each new ship at the bottom center of the screen.
self.rect.midbottom = self.screen_rect.midbottom
def blitme(self):
""" Draw ship at its current location. """
self.screen.blit(self.image, self.rect)
外星人入侵.py
import sys
import pygame
from ship import Ship
class AlienInvasion:
"""Overall class to manage game assets and behavior."""
def __init__(self):
"""Initialize the game, and create game resources."""
pygame.init()
self.screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption("Alien Invasion")
# Set background colour
self.bg_color = (0, 0, 255)
self.ship = Ship(self)
def run_game(self):
"""Start the main loop for the game."""
while True:
# Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# Redraw the screen during each pass through the loop.
self.screen.fill(self.bg_color)
self.ship.blitme()
# Make the most recently drawn screen visible.
pygame.display.flip()
if __name__ == '__main__':
# Make a game instance, and run the game.
ai = AlienInvasion()
ai.run_game()
I tried the answers from this discussion 但我无法修复它。
我不明白如何使用image.convert_alpha()
和image.set_colorkey()
,在ship.py 中使用它们对我来说没有任何变化。
注意:ship.py 是在船上进行更改的类,而 alieninvasion.py 是主文件。
【问题讨论】:
【参考方案1】:你不需要把图片的背景色改成窗口的背景色,只需要让图片的背景透明即可。
通过pygame.Surface.set_colorkey
设置透明色键:
设置 Surface 的当前颜色键。当将此 Surface 位图传输到目标上时,任何与颜色键颜色相同的像素都将是透明的。
注意,所有背景必须具有完全相同的颜色。在您的情况下,背景颜色似乎是灰色(230、230、230):
self.image = pygame.image.load('images/ship.bmp').convert()
self.image.set_colorkey((230, 230, 230))
另一种选择是创建一个新图像(您需要在绘画应用程序中绘制它),每像素 alpha(例如PNG)和透明背景:
self.image = pygame.image.load('images/ship.png').convert_alpha()
【讨论】:
以上是关于如何转换图像的背景颜色以匹配 Pygame 窗口的颜色?的主要内容,如果未能解决你的问题,请参考以下文章