在pygame

时间:2018-04-01 04:45:27

标签: python-3.x text pygame antialiasing alpha-transparency

我希望有一些文字,我可以更改alpha值,同时仍然让它消除锯齿效果。

label1是消除锯齿但不透明的

label2是透明的,但不是抗锯齿的

我想要的文字都是。 感谢。

import pygame
pygame.init()

screen = pygame.display.set_mode((300, 300))
font = pygame.font.SysFont("Segoe UI", 50)

label1 = font.render("hello", 1, (255,255,255))
label1.set_alpha(100)
label2 = font.render("hello", 0, (255,255,255))
label2.set_alpha(100)

surface_box = pygame.Surface((100,150))
surface_box.fill((0,150,150))

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

    screen.fill((150,0,150))
    screen.blit(surface_box, (40, 0))
    screen.blit(label1, (0,0))
    screen.blit(label2, (0,50))
    pygame.display.update()

pygame.quit()

如果您可以修改示例以获得这些功能,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

  1. 渲染文字表面。

  2. 通过传递pygame.SRCALPHA创建一个具有每像素alpha的透明曲面,并用白色和所需的alpha值填充它。

  3. 将alpha表面滑动到文本表面上,并将pygame.BLEND_RGBA_MULT作为special_flags参数传递。这将使表面的可见部分透明。

  4. import pygame as pg
    
    
    pg.init()
    clock = pg.time.Clock()
    screen = pg.display.set_mode((640, 480))
    font = pg.font.Font(None, 64)
    blue = pg.Color('dodgerblue1')
    sienna = pg.Color('sienna2')
    
    # Render the text surface.
    txt_surf = font.render('transparent text', True, blue)
    # Create a transparent surface.
    alpha_img = pg.Surface(txt_surf.get_size(), pg.SRCALPHA)
    # Fill it with white and the desired alpha value.
    alpha_img.fill((255, 255, 255, 140))
    # Blit the alpha surface onto the text surface and pass BLEND_RGBA_MULT.
    txt_surf.blit(alpha_img, (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((30, 30, 30))
        pg.draw.rect(screen, sienna, (105, 40, 130, 200))
        screen.blit(txt_surf, (30, 60))
        pg.display.flip()
        clock.tick(30)
    
    pg.quit()