How to make a circle semi-transparent in pygame?

2020-04-16 12:38发布

问题:

I'm somewhat new to pygame and trying to figure out how to make a circle semi-transparent. The trick however is that the background for the circle also has to be transparent. Here is the code I'm talking about:

size = 10
surface = pygame.Surface(size, size), pygame.SRCALPHA, 32)
pygame.draw.circle(
    surface, 
    pygame.Color("black"),
    (int(size/2), int(size/2)),
    int(size/2), 2)

I tried using surface.set_alpha(127) but that didn't work. I'm assuming because the surface is already transparent.

Any help is appreciated.

回答1:

A couple things. First, your surface definition should crash, as it missing a parenthesis. It should be:

surface = pygame.Surface((size, size), pygame.SRCALPHA, 32)

I assume that somewhere later in your code, you have something to the effect of:

mainWindow.blit(surface, (x, y))
pygame.display.update() #or flip

Here is your real problem:

>>> import pygame
>>> print pygame.Color("black")
(0, 0, 0, 255)

Notice that 255 at the end. That means that pygame.Color("black") returns a fully opaque color. Whereas (0, 0, 0, 0) would be fully transparent. If you want to set the transparency, define the color directly. That would make your draw function look like:

pygame.draw.circle(
    surface, 
    (0, 0, 0, transparency), 
    (int(size/2), int(size/2)),
    int(size/2), 2)


标签: python pygame