How to draw a transparent image in pygame?

后端 未结 3 890
长情又很酷
长情又很酷 2021-01-06 03:38

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


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-06 04:00

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

提交回复
热议问题