Pygame中的透明图像

4

我在Pygame中有一个蓝色圆形精灵,我希望这个图像被画出来时是“透明”的,比如半透明。但是,我不想在它上面绘制一个半透明矩形;相反,我想修改实际的图像并使其变得半透明。非常感谢任何帮助!

现在我有以下代码:

Class Circle(pygame.sprite.Sprite):

    self.image = self.image = pygame.image.load("circle.png")

circle = Circle()

最终...

window.blit(pygame.transform.scale(circle.image, (zoom, zoom)), (100, 100))

圆形图片的样子如下: enter image description here 将图片变为透明后,我想要图片的样子如下: enter image description here 我将图片贴到白色背景的窗口上。

1
也许提供 circle.png,在你绘制它的背景和第三张图片展示你想要的外观。一张图片胜过千言万语,所以3张图片可以节省你大量的写作时间。 - Mark Setchell
我添加了图片以展示我需要什么。 - Anish Shanbhag
3个回答

4

首先,你的图像/表面需要使用逐像素alpha通道,因此在加载时调用convert_alpha()方法。如果要创建新表面(例如示例中),还可以将pygame.SRCALPHA传递给pygame.Surface

第二步是创建另一个表面(此处称为alpha_surface),并用白色和所需的alpha值(颜色元组的第四个元素)填充。

最后,您必须将alpha_surface贴到图像上,并将special_flags参数设置为pygame.BLEND_RGBA_MULT。这将使图像的不透明部分变成半透明。

import pygame as pg


pg.init()
screen = pg.display.set_mode((800, 600))
clock = pg.time.Clock()
BLUE = pg.Color('dodgerblue2')
BLACK = pg.Color('black')

# Load your image and use the convert_alpha method to use
# per-pixel alpha.
# IMAGE = pygame.image.load('circle.png').convert_alpha()
# A surface with per-pixel alpha for demonstration purposes.
IMAGE = pg.Surface((300, 300), pg.SRCALPHA)
pg.draw.circle(IMAGE, BLACK, (150, 150), 150)
pg.draw.circle(IMAGE, BLUE, (150, 150), 130)

alpha_surface = pg.Surface(IMAGE.get_size(), pg.SRCALPHA)
# Fill the surface with white and use the desired alpha value
# here (the fourth element).
alpha_surface.fill((255, 255, 255, 90))
# Now blit the transparent surface onto your image and pass
# BLEND_RGBA_MULT as the special_flags argument. 
IMAGE.blit(alpha_surface, (0, 0), special_flags=pg.BLEND_RGBA_MULT)

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True

    screen.fill((50, 50, 50))
    pg.draw.rect(screen, (250, 120, 0), (100, 300, 200, 100))
    screen.blit(IMAGE, (150, 150))

    pg.display.flip()
    clock.tick(60)

pg.quit()

尽管我决定不在我的程序中使用透明度,但这确实做到了我想要的效果。谢谢! - Anish Shanbhag

0
创建一个带有每像素透明度的新表面。
surf = pygame.Surface((circle_width, circle_height), pygame.SRCALPHA)

使表面透明

surf.set_alpha(128)  # alpha value

在那个表面上画一个圆,坐标为(x=0, y=0)

surf.blit(pygame.transform.scale(circle.image, (zoom, zoom)), (0, 0))

将表面绘制到窗口中

window.blit(surf, (circle_x, circle_y))

0

正如Surface.set_alpha()文档所述,您可以拥有具有“均匀alpha”或逐像素alpha的表面,但不能同时拥有两者,这可能是您想要的。如果使用colorkey透明度,则可能有效,但我不确定(我尚未测试过)。任何非RGBA(没有活动alpha通道)像素格式都可能在blitting之前使用set_colorkey()set_alpha()

因此,代码可能如下所示:

class Circle(pygame.sprite.Sprite):
    def __init__(self)
        self.image = pygame.image.load("circle.png")
        # get the surface's top-left pixel color and use it as colorkey
        colorkey = self.image.get_at((0, 0))
        self.image.set_colorkey(colorkey)

在您的代码中的某个时刻(即渲染之前),您可能希望通过调用以下方法来设置透明度:
circle.image.set_alpha(some_int_val)

然后您可以按照预期进行缩放和位块传输。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接