how to use pygame set_alpha() on a picture

前端 未结 3 538
暖寄归人
暖寄归人 2020-12-06 13:38

I am using pygame and python for a project I am building, and I am building a splashscreen for when the game first opens. I have a .png that I want to show for the splashscr

3条回答
  •  庸人自扰
    2020-12-06 13:48

    Another problem that you might be having (besides what monkey said) is that you might need to use surface.convert() which converts the image into a form where the alpha can be changed. You can do either of the following.

    image = pygame.image.load("logo.png")
    image = image.convert()
    

    or

    image = pygame.image.load("logo.png").convert()
    

    I have found that, although surface.convert_alpha() should do pretty much the same thing, it doesn't usually work. Try this test code to check.

    import pygame, sys
    pygame.init()
    window=pygame.display.set_mode((1500, 800))
    background=pygame.Surface((window.get_rect().width, window.get_rect().height))
    background.fill((0, 0, 0))
    image=pygame.image.load('InsertImageHere.png')
    image=image.convert()
    image2=pygame.image.load('InsertImage2Here.png')
    image2=image2.convert_alpha()
    rect=image.get_rect()
    rect2=image2.get_rect()
    rect2.left=rect.width+1
    i=1
    while True:
        for event in pygame.event.get():
            if event.type==12:
                pygame.quit()
                sys.exit()
        image.set_alpha(i)
        image2.set_alpha(i)
        window.fill((255, 255, 255))
        window.blit(background, background.get_rect())
        window.blit(image, rect)
        window.blit(image2, rect2)
        pygame.time.delay(20)
        i+=1
        if i==255:
            i=1
        pygame.display.update()
    

    In my testings, image 1 faded in properly, but image 2 stayed dark the whole time. You should try it for yourself; your computer might work differently.

    If surface.convert_alpha() does work for you, you should use it, otherwise, do what I said before. This should solve your problem.

    You should also note that I used pygame.time.delay(20) rather than 2000 like you had before. 2000 would be a bit too long if you are increasing the alpha in incraments of one.

提交回复
热议问题