带有 alpha 的 Pygame 表面不闪烁透明度 [英] Pygame surface with alpha not blitting transparency
问题描述
当鼠标没有悬停在我的游戏中时,我试图让用户界面变得透明.但是出于某种原因,当我将图像的 alpha 值设置为透明时,没有任何反应.这是一些可运行的代码,可以复制问题:
I'm trying to make a user interface thing transparent in my game when the mouse isn't hovering over it. But for some reason, when I set the alpha value of the image for it to become transparent, nothing happens. Here is some runnable code for it that replicates the problem:
import pygame
WHITE = (255, 255, 255)
class UI:
def __init__(self):
self.img = pygame.image.load("ink_bar_solid.png")
self.img.set_alpha(0)
self.ink_bar_rect = self.img.get_bounding_rect()
self.x, self.y = 0, 10
resolution = (500, 500)
screen = pygame.display.set_mode(resolution)
mouse = pygame.mouse.get_pos
ink_bar = UI()
run = True
def mouse_over():
if ink_bar.ink_bar_rect.collidepoint(mouse()):
ink_bar.img.set_alpha(255)
else:
ink_bar.img.set_alpha(0)
while run:
mouse_over()
screen.fill(WHITE)
screen.blit(ink_bar.img, (ink_bar.x, ink_bar.y))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
break
pygame.display.flip()
pygame.quit()
非常感谢任何帮助!我从某人那里得到了一条评论,他说他们使用了自己的图像并且效果很好......我在执行程序时收到了这个警告:
Any help is greatly appreciated! I got a comment from someone who said they used their own image and it worked fine... I'm getting this warning when I execute the program:
libpng warning: iCCP: known incorrect sRGB profile
是不是因为我的文件而无法正确 blit 的原因?
Is the reason why it doesn't blit properly because of my file?
推荐答案
set_alpha
方法似乎不适用于未转换的 png 文件.调用 convert
方法还将显着提高 blit 性能:
The set_alpha
method doesn't seem to work for unconverted png files. Calling the convert
method will also improve the blit performance drastically:
self.img = pygame.image.load("ink_bar_solid.png").convert()
它也不适用于每像素 alpha 表面(使用 convert_alpha
转换的表面或使用 pygame.SRCALPHA
标志创建的表面).每像素表面的 alpha 可以通过用透明的白色填充它们并传递 pygame.BLEND_RGBA_MULT
特殊标志来改变,例如:
It also doesn't work for per-pixel alpha surfaces (surfaces converted with convert_alpha
or created with the pygame.SRCALPHA
flag). The alpha of per-pixel surfaces can be changed by filling them with a transparent white color and passing the pygame.BLEND_RGBA_MULT
special flag, e.g.:
image = pygame.image.load('an_image.png').convert_alpha()
# Make a copy so that the original doesn't get modified.
transparent_image = image.copy()
transparent_image.fill((255, 255, 255, 100), special_flags=pygame.BLEND_RGBA_MULT)
这篇关于带有 alpha 的 Pygame 表面不闪烁透明度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!