How to make a surface with a transparent background in pygame
This should do it:
image = pygame.Surface([640,480], pygame.SRCALPHA, 32)
image = image.convert_alpha()
Make sure that the color depth (32) stays explicitly set else this will not work.
Drawn surface transparency in pygame?
Have a look at the following example code:
import pygame
pygame.init()
screen = pygame.display.set_mode((300, 300))
ck = (127, 33, 33)
size = 25
while True:
if pygame.event.get(pygame.MOUSEBUTTONDOWN):
s = pygame.Surface((50, 50))
# first, "erase" the surface by filling it with a color and
# setting this color as colorkey, so the surface is empty
s.fill(ck)
s.set_colorkey(ck)
pygame.draw.circle(s, (255, 0, 0), (size, size), size, 2)
# after drawing the circle, we can set the
# alpha value (transparency) of the surface
s.set_alpha(75)
x, y = pygame.mouse.get_pos()
screen.blit(s, (x-size, y-size))
pygame.event.poll()
pygame.display.flip()
make a rect transparent in pygame
If you want to make the images transparent, you need to make sure that the alpha channel of the images is set. Additionally you must use convert_alpha()
instead of convert()
:
if ball_color:
ball = pygame.image.load("ball.png").convert_alpha()
else:
ball = pygame.image.load("medicine-ball.png").convert_alpha()
See also the answers to the questions:
- How to convert the background color of image to match the color of Pygame window?
- Pygame image transparency confusion
- pygame image background does not match main background
- How can I make an Image with a transparent Backround in Pygame?
make a rect transparent in pygame
Unfortunately there is no good way to draw a transparent shape. See the answers to the question Draw a transparent rectangle in pygame and see pygame.draw module:
A color's alpha value will be written directly into the surface [...], but the draw function will not draw transparently.
Hence you need to do a workaround:
- Create a
pygame.Surface
object with a per-pixel alpha format large enough to cover the shape. - Draw the shape on the _Surface.
- Blend the Surface with the target Surface.
blit()
by default blends 2 Surfaces
For example 3 functions, which can draw transparent rectangles, circles and polygons:
def draw_rect_alpha(surface, color, rect):
shape_surf = pygame.Surface(pygame.Rect(rect).size, pygame.SRCALPHA)
pygame.draw.rect(shape_surf, color, shape_surf.get_rect())
surface.blit(shape_surf, rect)
Use the function in your code instead of pygame.draw.rect
, alpha
is a value in range [0, 255]:
def rect(x1, y1, x2, y2, alpha = 255):
#pygame.draw.rect(screen, (0,0,0), (x1,y1,x2,y2))
draw_rect_alpha(screen, (0, 0, 0, alpha), (x1, y1, x2, y2))
Need to blit transparency on a surface in Pygame
You can create a surface with an alpha channel (pass the pygame.SRCALPHA
flag), fill it with an opaque color and then draw a shape with a transparent color onto it (alpha value 0).
import pygame as pg
pg.init()
screen = pg.display.set_mode((800, 600))
clock = pg.time.Clock()
BLUE = pg.Color('dodgerblue4')
# I just create the background surface in the following lines.
background = pg.Surface(screen.get_size())
background.fill((90, 120, 140))
for y in range(0, 600, 20):
for x in range(0, 800, 20):
pg.draw.rect(background, BLUE, (x, y, 20, 20), 1)
# This dark gray surface will be blitted above the background surface.
surface = pg.Surface(screen.get_size(), pg.SRCALPHA)
surface.fill(pg.Color('gray11'))
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.MOUSEMOTION:
surface.fill(pg.Color('gray11')) # Clear the gray surface ...
# ... and draw a transparent circle onto it to create a hole.
pg.draw.circle(surface, (255, 255, 255, 0), event.pos, 90)
screen.blit(background, (0, 0))
screen.blit(surface, (0, 0))
pg.display.flip()
clock.tick(30)
pg.quit()
You can also achieve this effect with another surface instead of pygame.draw.circle
. For example you could create a white image with some transparent parts in your graphics editor and pass BLEND_RGBA_MIN
as the special_flags argument to Surface.blit
when you blit it onto the gray surface.
brush = pg.image.load('brush.png').convert_alpha()
# Then in the while or event loop.
surface.fill(pg.Color('gray11'))
surface.blit(brush, event.pos, special_flags=pg.BLEND_RGBA_MIN)
Transparent Image in Pygame
First, your image/surface needs to use per-pixel alpha, therefore call the convert_alpha()
method when you load it. If you want to create a new surface (as in the example), you can also pass pygame.SRCALPHA
to pygame.Surface
.
The second step is to create another surface (called alpha_surface
here) which you fill with white and the desired alpha value (the fourth element of the color tuple).
Finally, you have to blit the alpha_surface
onto your image and pass pygame.BLEND_RGBA_MULT
as the special_flags
argument. That will make
the opaque parts of the image translucent.
import pygame as pg
pg.init()
screen = pg.display.set_mode((800, 600))
clock = pg.time.Clock()
BLUE = pg.Color('dodgerblue2')
BLACK = pg.Color('black')
# Load your image and use the convert_alpha method to use
# per-pixel alpha.
# IMAGE = pygame.image.load('circle.png').convert_alpha()
# A surface with per-pixel alpha for demonstration purposes.
IMAGE = pg.Surface((300, 300), pg.SRCALPHA)
pg.draw.circle(IMAGE, BLACK, (150, 150), 150)
pg.draw.circle(IMAGE, BLUE, (150, 150), 130)
alpha_surface = pg.Surface(IMAGE.get_size(), pg.SRCALPHA)
# Fill the surface with white and use the desired alpha value
# here (the fourth element).
alpha_surface.fill((255, 255, 255, 90))
# Now blit the transparent surface onto your image and pass
# BLEND_RGBA_MULT as the special_flags argument.
IMAGE.blit(alpha_surface, (0, 0), special_flags=pg.BLEND_RGBA_MULT)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
screen.fill((50, 50, 50))
pg.draw.rect(screen, (250, 120, 0), (100, 300, 200, 100))
screen.blit(IMAGE, (150, 150))
pg.display.flip()
clock.tick(60)
pg.quit()
Related Topics
Find Column Name in Pandas That Matches an Array
Numpy Sum Elements in Array Based on Its Value
How to Use Qscrollarea to Make Scrollbars Appear
Filling in Login Forms in Instagram Using Selenium and Webdriver (Chrome) Python Osx
Separation of Business Logic and Data Access in Django
How to Remove Packages Installed with Python's Easy_Install
Peak-Finding Algorithm for Python/Scipy
Convert a List of Characters into a String
Is a Python Dictionary an Example of a Hash Table
How to Set Timeout on Python's Socket Recv Method
How to Retrieve Inserted Id After Inserting Row in SQLite Using Python
Capture Keyboardinterrupt in Python Without Try-Except
Django - How to Create a File and Save It to a Model's Filefield