Pygame 中的透明精灵 [英] Transparent Sprites in Pygame
问题描述
我正在编写一些使用 Pygame 的 Python 代码,试图在背景上显示一个小精灵(一个球).我有那部分工作,但我试图让球精灵的背景透明,所以它不会显示为黑色方块内的球"精灵,而是显示黑色像素不是闪烁到显示表面.
I'm working on some Python code that uses Pygame, trying to display a small sprite (a ball) on top of a background. I have that part working, but I'm trying to get the background of the ball sprite to be transparent so it doesn't show up as a "ball within a black square" sprite, but instead shows up with the black pixels not being blitted to the display surface.
这是我的代码:
# 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".我错过了一步吗?
I must be making an obvious mistake, but I can't figure it out. Calling ball.set_colorkey(-1, RLEACCEL) should pick up the color of the upper-left corner of the ball sprite (which happens to be black) and use that as the pixel color "not to blit". Am I missing a step?
感谢您的帮助.
推荐答案
有每像素 alpha、颜色键 alpha 和每表面 alpha.您要的是色键.
There's per-pixel alpha, colorkey alpha, and per-surface alpha. You're asking for colorkey.
当您调用 convert_alpha()
它为每像素 alpha 创建一个新表面.
When you call convert_alpha()
it creates a new surface for per-pixel alpha.
来自 set_colorkey
如果 Surface 格式化为使用每像素 alpha 值,则颜色键将被忽略.
The colorkey will be ignored if the Surface is formatted to use per pixel alpha values.
所以:使用 .convert()
加载图像 因为您想使用颜色键.然后调用set_colorkey
.
So: Load image with .convert()
Since you want to use a color key. Then call set_colorkey
.
此外,我在文档中没有看到任何关于将-1"作为第一个参数传递给 set_colorkey 的内容.
Also, I saw nothing in the docs about passing "-1" as first argument to set_colorkey.
这可能来自一个教程,它有一个 load_image 函数来获取左上角像素的颜色值.
That's probably from a tutorial, which has a load_image function to grab the topleft pixel's color value.
这篇关于Pygame 中的透明精灵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!