Skip to content
Advertisement

How to render transparent text with alpha channel in PyGame?

I am using pygame.font.Font.render() to render some text. I’d like the text to be translucent, ie have an alpha value other than 255, so I tried passing a color argument with an alpha value (eg (255, 0, 0, 150)) as the color argument for pygame.font.Font.render() but it didn’t have any effect. I also tried using pygame.Surface.convert_alpha() on the resulting Surface object, but that didn’t do anything either. Any ideas?

Advertisement

Answer

When using the pygame.font module, the alpha channel of the text color is not taken into account when rendering a text, but see pygame.font.Font.render:

Antialiased images are rendered to 24-bit RGB images. If the background is transparent a pixel alpha will be included.

and pygame.Surface.set_alpha

Changed in pygame 2.0: per-surface alpha can be combined with per-pixel alpha.

Hence it is completely sufficient to set the transparency after rendering the text with set_alpha. This even works for anti-aliased text:

JavaScript

Minimal example: repl.it/@Rabbid76/PyGame-TransparentText

JavaScript

By using the pygame.freetype module, you can use a transparent color directly when creating a text surface:

JavaScript

Or if you are rendering the text directly onto a surface:

JavaScript

Minimal example: repl.it/@Rabbid76/PyGame-TransparentFreeTypeText

JavaScript

See also Text and font

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement