Draw a transparent rectangle in pygame

2019-01-10 17:25发布

How can I draw a rectangle that has a color with an alpha? I have:

windowSurface = pygame.display.set_mode((1000, 750), pygame.DOUBLEBUF)
pygame.draw.rect(windowSurface, pygame.Color(255, 255, 255, 128), pygame.Rect(0, 0, 1000, 750))

But I want the white rectangle to be 50% transparent, but the alpha value doesn't appear to be working.

标签: python pygame
3条回答
可以哭但决不认输i
2楼-- · 2019-01-10 18:04

You can add a fourth value to your color tuple to represent Alpha:

pygame.draw.rect(windowSurface, (255, 255, 255, 127), pygame.Rect(0, 0, 1000, 750))
查看更多
贼婆χ
3楼-- · 2019-01-10 18:11

pygame.draw functions will not draw with alpha. The documentation says:

Most of the arguments accept a color argument that is an RGB triplet. These can also accept an RGBA quadruplet. The alpha value will be written directly into the Surface if it contains pixel alphas, but the draw function will not draw transparently.

What you can do is create a second surface and then blit it to the screen. Blitting will do alpha blending and color keys. Also, you can specify alpha at the surface level (faster and less memory) or at the pixel level (slower but more precise). You can do either:

s = pygame.Surface((1000,750))  # the size of your rect
s.set_alpha(128)                # alpha level
s.fill((255,255,255))           # this fills the entire surface
windowSurface.blit(s, (0,0))    # (0,0) are the top-left coordinates

or,

s = pygame.Surface((1000,750), pygame.SRCALPHA)   # per-pixel alpha
s.fill((255,255,255,128))                         # notice the alpha value in the color
windowSurface.blit(s, (0,0))

Keep in mind in the first case, that anything else you draw to s will get blitted with the alpha value you specify. So if you're using this to draw overlay controls for example, you might be better off using the second alternative.

Also, consider using pygame.HWSURFACE to create the surface hardware-accelerated.

Check the Surface docs at the pygame site, especially the intro.

查看更多
姐就是有狂的资本
4楼-- · 2019-01-10 18:14

the most i can do to help you is to show you how to draw a rectangle that is not filled in. the line for the rectangle is:

pygame.draw.rect(surface, [255, 0, 0], [50, 50, 90, 180], 1)

the "1" means that it is not filled in

查看更多
登录 后发表回答