Home > Net >  How to blit image in multilayer pygame without blending
How to blit image in multilayer pygame without blending

Time:08-14

I'm trying to create a chessgame using pygame. I got a screen with two layers blitted on it. One being the chessboard and the other one with the figures. In order to update the screen, I'm blitting the layers onto the Screen. First the chessboard, then the figure layer. However I couldn't find a way of doing this successfully without using a blend option as a special flag. This causes the figures to look different depending on which square they are (black, white background). I tried doing it without the blending option but that results into me not being able to draw the chessboard layer.

The chessboard layer is drawn by using pygame.draw.rect(). The figures are drawn by using surface.blit().

Following code is the setup of the layers.

self.WIN = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
self.CHESSBOARD_LAYER = pygame.Surface((self.WIDTH,self.HEIGHT))
self.FIGURE_LAYER = pygame.Surface((self.WIDTH,self.HEIGHT))

Following code is being used in order to draw the chessboard and the figure layer.

self.WIN.fill("#000000")
self.WIN.blit(self.CHESSBOARD_LAYER,(0,0), special_flags=pygame.BLEND_RGB_ADD)
self.WIN.blit(self.FIGURE_LAYER,(0,0), special_flags=pygame.BLEND_RGB_ADD)
pygame.display.update()

Not using the .BLEND_RGB_ADD or other blend parameters results in a black screen with the image of the figure ontop of it (not drawing the chessboard).

I've also tried different blending options but didn't find one to work for me.

Image looks like this while the pawn on the black background looks as it should be but the other ones are affected by the background.

CodePudding user response:

The problem is that your layer surface have no alpha channel. You create a Surface without alpha channel (RGB). You have to use the SRCALPHA flag to create a Surface with an alpha channel (RGBA). Also see pygame.Surface:

self.CHESSBOARD_LAYER = pygame.Surface((self.WIDTH, self.HEIGHT), pygame.SRCALPHA)
self.FIGURE_LAYER = pygame.Surface((self.WIDTH, self.HEIGHT), pygame.SRCALPHA)

Now you don't need any special blending flag at all:

self.WIN.fill("#000000")
self.WIN.blit(self.CHESSBOARD_LAYER, (0, 0))
self.WIN.blit(self.FIGURE_LAYER, (0, 0))
pygame.display.update()

Note, with the flag SRCALPHA each pixel has its own alpha value (RGBA format), without the flag the surfaces hast just 1 global alpha value and can not store different alpha values for the pixels (RGB format).

  • Related