pygame draw transparent rectangle
You can draw a transparent rectangle in pygame by using the set_alpha()
method of the Surface
class. Here's an example:
import pygame
# Initialize pygame
pygame.init()
# Set the width and height of the screen
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
# Set the transparency value
alpha = 128
# Create a surface with the desired dimensions and transparency
rect_surface = pygame.Surface((200, 100), pygame.SRCALPHA)
# Set the transparency value for the surface
rect_surface.set_alpha(alpha)
# Draw a rectangle on the surface
rect_color = (255, 0, 0) # Red color
rect_position = (300, 200) # Position of the rectangle
rect_size = (200, 100) # Size of the rectangle
pygame.draw.rect(rect_surface, rect_color, (0, 0, *rect_size))
# Blit the surface onto the screen
screen.blit(rect_surface, rect_position)
# Update the screen
pygame.display.flip()
# Event loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Quit pygame
pygame.quit()
This code will create a transparent rectangle with a red color and blit it onto the screen using the blit()
function. The transparency value is set using the set_alpha()
method of the Surface
class. The pygame.SRCALPHA
flag is passed to the Surface
constructor to enable per-pixel alpha blending.