Reputation: 81
I need a way to draw a partially transparent line in pygame. I found this answer(python - Draw a transparent Line in pygame) but it only works with straight lines and doesn't work with different line thicknesses.
Upvotes: 2
Views: 694
Reputation: 143216
You have to create new surface with any size and with alpha
channel
surface = pygame.Surface((width, height)).convert_alpha()
or use main surface to create new surface with the same size
surface = screen.convert_alpha()
Fill it with transparent color (0,0,0,0)
. Important is last zero which means alpha
channel - (R,G,B,A)
surfaces.fill([0,0,0,0])
Draw on this surface with alpha channel smaller then 255
pygame.draw.line(surface, (0, 0, 0, 32), (0, 0), (800, 600), 5)
And finally you can blit it on main page in any place
screen.blit(surface, (x, y))
For surface which has the same size as main surface it can be (0,0)
screen.blit(surface, (0,0))
Minimal example
import pygame
pygame.init()
screen = pygame.display.set_mode((800,600))#, depth=32)
surface1 = screen.convert_alpha()
surface1.fill([0,0,0,0])
pygame.draw.circle(surface1, (255, 0, 0, 128), (325, 250), 100)
surface2 = screen.convert_alpha()
surface2.fill([0,0,0,0])
pygame.draw.circle(surface2, (0, 255, 0, 128), (475, 250), 100)
surface3 = screen.convert_alpha()
surface3.fill([0,0,0,0])
pygame.draw.circle(surface3, (0, 0, 255, 128), (400, 350), 100)
surface4 = screen.convert_alpha()
surface4.fill([0,0,0,0])
pygame.draw.line(surface4, (0, 0, 0, 32), (0, 0), (800, 600), 5)
pygame.draw.line(surface4, (0, 0, 0, 32), (0, 600), (800, 0), 5)
surface5 = screen.convert_alpha()
surface5.fill([0,0,0,0])
pygame.draw.polygon(surface5, (255, 0, 0, 128), [(400, 250), (450, 300), (400, 350), (350, 300)])
screen.fill([255,255,255]) # white background
screen.blit(surface1, (0,0))
screen.blit(surface2, (0,0))
screen.blit(surface3, (0,0))
screen.blit(surface4, (0,0))
screen.blit(surface5, (0,0))
pygame.display.flip()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
pygame.quit()
Upvotes: 3