python 如何在 Pygame 中将具有一定透明度的 PNG 闪烁到表面上?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1634208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I blit a PNG with some transparency onto a surface in Pygame?
提问by Eric
I'm trying to blit a PNG image onto a surface, but the transparent part of the image turns black for some reason, here's the simple code:
我正在尝试将 PNG 图像 blit 到一个表面上,但由于某种原因,图像的透明部分变黑了,这是简单的代码:
screen = pygame.display.set_mode((800, 600), pygame.DOUBLEBUF, 32)
world = pygame.Surface((800, 600), pygame.SRCALPHA, 32)
treeImage = pygame.image.load("tree.png")
world.blit(treeImage, (0,0), (0,0,64,64))
screen.blit(world, pygame.rect.Rect(0,0, 800, 600))
What do I have to do to solve the problem? The image has alpha transparency, I've opened it up in PhotoShop and the background turns transparent, not black or white or any other color.
我该怎么做才能解决问题?该图像具有 alpha 透明度,我已在 PhotoShop 中打开它,背景变为透明,而不是黑色或白色或任何其他颜色。
Thank you for your support :)
谢谢您的支持 :)
回答by Nick T
http://www.pygame.org/docs/ref/image.htmlrecommends:
http://www.pygame.org/docs/ref/image.html建议:
For alpha transparency, like in .png images use the
convert_alpha()
method after loading so that the image has per pixel transparency.
对于 alpha 透明度,如在 .png 图像中使用
convert_alpha()
加载后的方法,以便图像具有每个像素的透明度。
回答by Guest
You did not flip the doublebuffer.
您没有翻转双缓冲区。
import pygame
from pygame.locals import Color
screen = pygame.display.set_mode((800, 600))
treeImage = pygame.image.load("tree.png").convert_alpha()
white = Color('white')
while(True):
screen.fill(white)
screen.blit(treeImage, pygame.rect.Rect(0,0, 128, 128))
pygame.display.flip()
This should work for your problem.
这应该可以解决您的问题。
回答by Peter Shinners
Your code looks like it should be correct. The SDL library does not support alpha to alpha blitting like this, but Pygame added support for it awhile ago. In Pygame 1.8 support was added for custom blending modes, and I wonder if that removed Pygame's internal alpha-to-alpha blitter?
您的代码看起来应该是正确的。SDL 库不支持像这样的 alpha 到 alpha blitting,但 Pygame 不久前添加了对它的支持。在 Pygame 1.8 中添加了对自定义混合模式的支持,我想知道这是否删除了 Pygame 的内部 alpha-to-alpha blitter?
Alas, further investigation will be required.
唉,还需要进一步调查。