Saurabh Shrivastava
Saurabh Shrivastava

Reputation: 1484

How to draw a transparent image in pygame?

Consider a chess board, i have a transparent image of queen(queen.png) of size 70x70 and i want to display it over a black rectangle. Code:

BLACK=(0,0,0)
queen = pygame.image.load('queen.png')

pygame.draw.rect(DISPLAYSURF, BLACK, (10, 10, 70, 70))
DISPLAYSURF.blit(queen, (10, 10))

Error: i am not getting transparent image ie black rectangle is not visible at all, only queen with white background. Please suggest

Upvotes: 5

Views: 14471

Answers (3)

elegent
elegent

Reputation: 4007

When you call the pygame.image.load() method, Pygame reads an image file from your hard drive and returns a surface object containing the image data. This surface instance is the same type of object as your display surface, but it represents an image stored in memory.

By calling the convert() method of an (image-) surface instance with no arguments passed, Pygame converts the image surface to the same format as your main display surface. This is recommended, because it is faster to draw or blit images which have the same pixel format (depth, flags etc.) as the display surface. When you use this method, the converted surface will have no alpha information.

Fortunately Pygame surface objects provide also a convert_alpha() method, which converts an (image-) surface to a fast format that preserves any alpha information.

This means you need to call the convert_alpha() method of your queen instance for preserving any alpha information of the original image:

BLACK=(0,0,0)

#load the image and convert the returned surface using the convert_alpha() method
queen = pygame.image.load('queen.png').convert_alpha() 

pygame.draw.rect(DISPLAYSURF, BLACK, (10, 10, 70, 70))
DISPLAYSURF.blit(queen, (10, 10))
pygame.display.update()

Upvotes: 4

Leafthecat
Leafthecat

Reputation: 336

Try changing the line where you load in the queen to:

queen = pygame.image.load('queen.png').convert_alpha()

Upvotes: 10

tomisy
tomisy

Reputation: 21

I don't think pygame.draw.rect supports alpha channels. You should use pygame.Surface

queen = pygame.Surface([10, 10], pygame.SRCALPHA, 32)

Upvotes: 2

Related Questions