Pygame - 图像/曲面的平滑变换

时间:2017-12-06 19:32:19

标签: python pygame

有没有办法在一个图像和另一个图像之间创建平滑过渡?

说我有图像X和图像Y

ImageX = pygame.image.load('foo.png')
ImageY = pygame.image.load('oof.png')

当W = 5时,图像X转换为图像Y. 通常,我会在绘图代码中执行此操作:

if w == 5:
    screen.blit(ImageY, (100, 100))
else:
    screen.blit(ImageX, (100, 100))

但是这只会让图像X被ImageY取代,一帧是imageX,另一帧是imageY

如何让ImageX顺利过渡到ImageY?就像css中的transition属性一样。

2 个答案:

答案 0 :(得分:2)

您可以使用set_alpha

将透明度(0-255)指定给曲面
ImageX.set_alpha(128)

当您在ImagaX之后快速ImageY时,您应该看到两张图片。

blit(ImageY, ...)
blit(ImageX, ...)

您必须仅在循环中将set_alpha()(从255更改为0)才能获得平滑的效果。

if transparency > 0
     transparency -= 1 

ImageX.set_alpha(transparency)

blit(ImageY, ...)
blit(ImageX, ...)

BTW:可能要使用set_alpha()图片必须使用convert(),而不是convert_alpha()

请参阅我在GitHub上的示例:pygame - transparency

答案 1 :(得分:1)

要设置每像素alpha的图像的alpha /透明度,您需要使用一个小技巧。您可以创建一个中间曲面,用白色和所需的alpha值填充它,然后使用pygame.BLEND_RGBA_MULT标志将其blit到另一个曲面上。这将保持完全透明的像素不变,只是改变可见部分的透明度。

因此,如果你想淡入一个表面而另一个表面淡出,你只需存储它们的alpha值,每帧更改它们,然后调用change_alpha函数来获得具有正确透明度的新曲面。 (我在这个例子中使用了文本表面,但它也适用于其他表面/加载的图像)。

import pygame as pg


def change_alpha(orig_surf, alpha):
    """Create a copy of orig_surf with the desired alpha value.

    This function creates another surface with the desired alpha
    value and then blits it onto the copy of the original surface
    with the `BLEND_RGBA_MULT` flag to change the transparency."""
    surf = orig_surf.copy()
    # This surface is used to adjust the alpha of the txt_surf.
    alpha_surf = pg.Surface(surf.get_size(), pg.SRCALPHA)
    alpha_surf.fill((255, 255, 255, alpha))  # Set the alpha value.
    surf.blit(alpha_surf, (0, 0), special_flags=pg.BLEND_RGBA_MULT)
    return surf


def main():
    clock = pg.time.Clock()
    screen = pg.display.set_mode((640, 480))
    font = pg.font.Font(None, 64)

    # The original surface which will never be modified.
    orig_surf = font.render('Enter your text', True, pg.Color('dodgerblue'))
    alpha = 255  # The current alpha value of the surface.

    # Surface 2
    orig_surf2 = font.render('Another text surface', True, pg.Color('sienna1'))
    alpha2 = 0

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

        if alpha > 0:
            # Reduce alpha each frame.
            alpha -= 4
            alpha = max(0, alpha)  # Make sure it doesn't go below 0.
            surf = change_alpha(orig_surf, alpha)
        if alpha2 < 255:
            alpha2 += 4
            alpha2 = min(255, alpha2)
            surf2 = change_alpha(orig_surf2, alpha2)

        screen.fill((30, 30, 30))
        screen.blit(surf, (30, 60))
        screen.blit(surf2, (30, 60))
        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
相关问题