gpt4 book ai didi

python - 如何在图片上使用pygame set_alpha()

转载 作者:太空宇宙 更新时间:2023-11-03 12:19:17 24 4
gpt4 key购买 nike

我正在为我正在构建的项目使用 pygame 和 python,并且正在为游戏首次打开时构建启动画面。我有一个 .png 想要显示在初始屏幕上,并决定将其淡入和淡出黑色。我发现做到这一点的最佳方法是使用设置的 alpha block 化图像。我编写了这段代码,但它运行得非常慢(程序挂起 30 秒)并且没有给出 alpha。仅在屏幕上显示图片。我做错了什么?

screen = pygame.display.set_mode([1066,600])

#Drawable surface
background = pygame.Surface(screen.get_size())

#Used for converting color maps
background = background.convert()

#Splashscreen

#image fades in
for i in range (225):
background.fill((0,0,0))
image = pygame.image.load("logo.png")
image.set_alpha(i)
logoimage = screen.blit(image,(0,0))
pygame.display.flip()

pygame.time.delay(2000)

#image fades out

#goes on to display main menu

最佳答案

您可能遇到的另一个问题(除了猴子所说的)是您可能需要使用 surface.convert() 将图像转换为可以更改 alpha 的形式。您可以执行以下任一操作。

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

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

我发现,虽然 surface.convert_alpha() 应该做几乎相同的事情,但它通常不起作用。尝试使用此测试代码进行检查。

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

在我的测试中,图片 1 淡入正常,但图片 2 始终保持黑暗。你应该亲自尝试一下;您的计算机可能工作方式不同。

如果 surface.convert_alpha() 对你有用,你应该使用它,否则,按照我之前说的做。这应该可以解决您的问题。

您还应注意,我使用的是 pygame.time.delay(20) 而不是您之前使用的 2000。如果以 1 的增量增加 alpha,2000 会有点太长。

关于python - 如何在图片上使用pygame set_alpha(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12255558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com