Pygame surface with alpha not blitting transparency

℡╲_俬逩灬. 提交于 2021-01-28 03:30:19

问题


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! Edit: 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

Is the reason why it doesn't blit properly because of my file?


回答1:


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()

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)


来源:https://stackoverflow.com/questions/53137497/pygame-surface-with-alpha-not-blitting-transparency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!