Skip to main content
Engineering LibreTexts

3.11: Transparent Colors

  • Page ID
    14419
  • When you look through a glass window that has a deep red tint, all of the colors behind it have a red shade added to them. You can mimic this effect by adding a fourth 0 to 255 integer value to your color values.

    This value is known as the alpha value. It is a measure of how opaque (that is, not transparent) a color is. Normally when you draw a pixel onto a surface object, the new color completely replaces whatever color was already there. But with colors that have an alpha value, you can instead just add a colored tint to the color that is already there.

    For example, this tuple of three integers is for the color green: (0, 255, 0). But if we add a fourth integer for the alpha value, we can make this a half transparent green color: (0, 255, 0, 128). An alpha value of 255 is completely opaque (that is, no transparency at all). The colors (0, 255, 0) and (0, 255, 0, 255) look exactly the same. An alpha value of 0 means the color is completely transparent. If you draw any color that has an alpha value of 0 to a surface object, it will have no effect, because this color is completely transparent and invisible.

    In order to draw using transparent colors, you must create a Surface object with the convert_alpha() method. For example, the following code creates a Surface object that transparent colors can be drawn on:

    anotherSurface = DISPLAYSURF.convert_alpha()
    

    Once things have been drawn on the Surface object stored in anotherSurface, then anotherSurface can be "blitted" (that is, copied) to DISPLAYSURF so it will appear on the screen. (See the "Drawing Images with pygame.image.load() and blit()" section later in this chapter.)

    It’s important to note that you cannot use transparent colors on Surface objects not returned from a convert_alpha() call, including the display Surface that was returned from pygame.display.set_mode().

    If we were to create a color tuple to draw the legendary Invisible Pink Unicorn, we would use (255, 192, 192, 0), which ends up looking completely invisible just like any other color that has a 0 for its alpha value. It is, after all, invisible.

    Figure 7

    Figure \(\PageIndex{1}\): Above is a screenshot of a drawing of the Invisible Pink Unicorn.
    • Was this article helpful?