How to draw a transparent image in pygame?

允我心安 提交于 2019-12-10 16:46:53

问题


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


回答1:


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

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



回答2:


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()



回答3:


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

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


来源:https://stackoverflow.com/questions/28645597/how-to-draw-a-transparent-image-in-pygame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!