【问题标题】:Transparent Sprites in PygamePygame 中的透明精灵
【发布时间】:2012-10-24 22:55:28
【问题描述】:

我正在编写一些使用 Pygame 的 Python 代码,试图在背景上显示一个小精灵(一个球)。我有那部分工作,但我试图让球精灵的背景是透明的,所以它不会显示为“黑色正方形内的球”精灵,而是显示黑色像素不是blitted 到显示表面。

这是我的代码:

# For sys.exit()
import sys

# Pygame imports
import pygame
from pygame.locals import *

# Initialize all the Pygame Modules
pygame.init()

# Build a screen (640 x 480, 32-bit color)
screen = pygame.display.set_mode((640,480)) 

# Create and Convert image files
# Use JPG files for lots of color, and use conver()
# Use PNG files for transparency, and use convert_alpha()
background = pygame.image.load("bg.jpg").convert()
ball = pygame.image.load("ball.png").convert_alpha()
ball.set_colorkey(-1, RLEACCEL) # Use the upper-left pixel color as transparent

# The main loop
while True:

    # 1 - Process all input events
    for event in pygame.event.get():

        # Make sure to exit if the user clicks the X box
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    # 2 - Blit images to screen (main display window)
    screen.blit(background, (0,0))
    x,y = pygame.mouse.get_pos()
    x = x - ball.get_width()/2
    y = y - ball.get_height()/2
    screen.blit(ball, (x,y))

    # 3 - Update the main screen (redraw)
    pygame.display.update()

我一定是犯了一个明显的错误,但我想不通。调用 ball.set_colorkey(-1, RLEACCEL) 应该获取球精灵左上角的颜色(恰好是黑色),并将其用作“不 blit”的像素颜色。我错过了一步吗?

感谢您的帮助。

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    有逐像素 alpha、colorkey alpha 和逐表面 alpha。你要的是颜色键。

    当您调用 convert_alpha() 时,它会为每像素 alpha 创建一个新表面。

    来自set_colorkey

    如果 Surface 被格式化为使用每像素 alpha 值,则颜色键将被忽略。

    所以:使用.convert() 加载图像因为您想使用颜色键。然后拨打set_colorkey

    另外,我在文档中没有看到关于将“-1”作为第一个参数传递给 set_colorkey。

    这可能来自一个教程,它有一个 load_image 函数来获取左上角像素的颜色值。

    【讨论】:

    • 非常感谢。这解决了我的问题
    【解决方案2】:

    您的图像是如何创建的? 如果您的“ball.png”文件是透明背景上的球,而不是黑色方块上的球,则用于 blitting 的 Pygame 透明度应该可以工作。 也就是说,来自 Pygame 的“set_colorkey”表面文档:

    “如果 Surface 被格式化为使用每像素 alpha 值,则 colorkey 将被忽略。colorkey 可以与完整的 Surface alpha 值混合。”

    因此,colorkey 的想法是在您的图像没有每像素 alpha 时使用它 - 而您只是确保它在您调用“convert alpha”时确实具有。此外,我在文档中没有看到关于将“-1”作为第一个参数传递给 set_colorkey。

    简而言之:我的建议是使用适当的透明图像开始 - 忘记“convert”、“convert_alpha”、“set_colorkey”等。如果您有某些原因不使用 PNG 文件中的每像素 alpha,那么请检查这个答案是否正确(甚至出于一个原因,在传输到屏幕时不想要每像素 alpha): PyGame: Applying transparency to an image with alpha?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-09
      • 2017-04-25
      相关资源
      最近更新 更多