2

I want to have text which I can change the alpha value for while still having it anti-aliased to look good.

label1 is anti-aliased but not transparent

label2 is transparent but not antialiased

I want text which is both. Thanks.

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

If you could modify the example to have these features it would be appreciated.

vbscript
  • 23
  • 5

1 Answers1

2
  1. Render the text surface.

  2. Create a transparent surface with per-pixel alpha by passing pygame.SRCALPHA and fill it with white and the desired alpha value.

  3. Blit the alpha surface onto the text surface and pass pygame.BLEND_RGBA_MULT as the special_flags argument. This will make the visible parts of the surface transparent.


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()
skrx
  • 19,980
  • 5
  • 34
  • 48