Reputation: 11
I'm trying to make a color picker that changes color over time. I have the logic but the process is really slow, the idea is to have a square that changes color and overlap a PNG grayscale gradient onto it so that the program can be faster. The problem is that I can't seem to download the gradient with the transparency.
import sys, pygame
pygame.init()
#VARIABLES
width = 255
height = 255
background = (255, 0, 0)
foreground = (230, 100, 45)
mySurf = pygame.Surface((255, 255))
mySurf.set_alpha(0)
mySurf.fill((200,0,200))
#SCREEN
screen = pygame.display.set_mode((width, height))
screen.fill((0, 0, 0))
#CODE
for x in range(255):
s = pygame.Surface((1, 255))
s.set_alpha(255-x)
s.fill((255, 255, 255))
mySurf.blit(s, (x, 0))
for y in range(255):
s = pygame.Surface((255, 1))
s.set_alpha(y)
s.fill((0, 0, 0))
mySurf.blit(s, (0, y))
pygame.image.save(mySurf, "gradient.png")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
Upvotes: 1
Views: 217
Reputation: 210880
You have to create a surface with a format that hast an alpha channel per pixel. Use the SRCALPHA
flag:
mysurf = pygame.surface((255, 255))
mySurf = pygame.Surface((255, 255), pygame.SRCALPHA)
Note, with the flag each pixel has its own alpha value (RGBA format), without the flag the surfaces hast just 1 global alpha value and can not store different alpha values for the pixels (RGB format)
Complete example:
import sys, pygame
pygame.init()
#VARIABLES
width = 255
height = 255
background = (255, 0, 0)
foreground = (230, 100, 45)
mySurf = pygame.Surface((255, 255))
mySurf.set_alpha(0)
mySurf.fill((200,0,200))
#SCREEN
screen = pygame.display.set_mode((width, height), pygame.SRCALPHA)
#CODE
s = pygame.Surface((1, 255), pygame.SRCALPHA)
for x in range(255):
s.fill((255, 255, 255, 255-x))
mySurf.blit(s, (x, 0))
s = pygame.Surface((255, 1), pygame.SRCALPHA)
for y in range(255):
s.fill((0, 0, 0, y))
mySurf.blit(s, (0, y))
pygame.image.save(mySurf, "gradient.png")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
Upvotes: 1