4

I am trying to draw simple semi-transparent rectangle in pygame. I have tried this code:

import pygame, sys,pygame.mixer

pygame.init()
size = (width, height) = (400, 400)
screen = pygame.display.set_mode(size)
screen.fill((255,255,255))
pygame.draw.rect(screen, (23, 100, 255, 50), (100,100,100,100),0)

running = True
while running:
    for event in pygame.event.get():
       if event.type == pygame.QUIT:
            pygame.quit()
            running = False

But as you can see, the rectangle is not semi-transparent. It's like I inserted the color 23, 100, 255, 255) rather than (23, 100, 255, 50).

user202729
  • 3,358
  • 3
  • 25
  • 36
user1767774
  • 1,775
  • 3
  • 24
  • 32

3 Answers3

6

You can also use gfxdraw which has several options and accepts alpha in color.

You'll need to import:

import pygame.gfxdraw

And use with:

pygame.gfxdraw.box(screen, pygame.Rect(0,0,200,200), (100,0,0,127))
Gustavo J.C.
  • 316
  • 4
  • 8
5

pygame.draw.rect documentation doesn't state support for alpha channel.

You should create a RGBA surface and fill it with the semi transparent color:

rect = pygame.Surface((100,100), pygame.SRCALPHA, 32)
rect.fill((23, 100, 255, 50))
screen.blit(rect, (100,100))
pmoleri
  • 4,238
  • 1
  • 15
  • 25
0

I asked a question similar to this here. What I ended up doing was using the set_alpha() function after converting it to an alpha image. You may find something helpful in my question. Also, make sure you're not showing an older version of the rectangle that has 100% opacity behind the one that is semi-transparent.

Community
  • 1
  • 1
Ben Schwabe
  • 1,283
  • 1
  • 21
  • 36