How to make pygame.surface transparent

How to make pygame.surface transparent

Postby hansn » Tue Apr 23, 2013 4:10 pm

I want to draw a tank using pygame.draw with a square(the body) and a triangle(the canon). To account for collision I'm using the sprite module, and because of that I think I have to use a pygame.surface-square to draw on (?). After drawing the square and the canon on the surface, there is some space left (not drawn on) on it, and I would like to make it transparent.

If there are better ways to do this (draw your own figures with pygame.draw and easily account for collision) I would love to hear them.

Thanks.
hansn
 
Posts: 87
Joined: Thu Feb 21, 2013 8:46 pm

Re: How to make pygame.surface transparent

Postby Mekire » Tue Apr 23, 2013 5:00 pm

Quick dirty example. Green tank with a transparent background that is then drawn on a blue screen.

Method one. Using a colorkey (when it is possible, this is the best solution):
Code: Select all
import pygame,sys
pygame.init()
screen = pygame.display.set_mode((500,500))

image = pygame.Surface((100,100)).convert()
image.fill((255,0,255))
image.set_colorkey((255,0,255))
image.fill((0,255,0),(25,25,50,50))
pygame.draw.polygon(image,(0,255,0),[(25,35),(25,65),(0,50)])
rect = image.get_rect(center=(250,250))

while 1:
    for ev in pygame.event.get():
            if ev.type==pygame.QUIT:
                pygame.quit();sys.exit()
    screen.fill((0,0,255))
    screen.blit(image,rect)
    pygame.display.flip()

Method two. Using a surface with per-pixel alpha:
Code: Select all
import pygame,sys
pygame.init()
screen = pygame.display.set_mode((500,500))

image = pygame.Surface((100,100)).convert_alpha()
image.fill((0,0,0,0))
image.fill((0,255,0),(25,25,50,50))
pygame.draw.polygon(image,(0,255,0),[(25,35),(25,65),(0,50)])
rect = image.get_rect(center=(250,250))

while 1:
    for ev in pygame.event.get():
            if ev.type==pygame.QUIT:
                pygame.quit();sys.exit()
    screen.fill((0,0,255))
    screen.blit(image,rect)
    pygame.display.flip()

Hope this helps. Also keep in mind using the Sprite class doesn't change anything. Pygame surfaces are pygame surfaces. Collision is collision. You may or may not find it easier with the sprite class, but don't build any illusions about what it is and is not.

-Mek
User avatar
Mekire
 
Posts: 821
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: How to make pygame.surface transparent

Postby hansn » Tue Apr 23, 2013 7:33 pm

Thanks!
hansn
 
Posts: 87
Joined: Thu Feb 21, 2013 8:46 pm


Return to Game Development

Who is online

Users browsing this forum: No registered users and 2 guests

cron