How to use pygame.fill to set pixels with alpha value instead of blending them in pygame

30 views Asked by At

So, I was trying to create a CropView for my pygame gui library. Now that doesn't really matter, the problem at hand is. Suppose I have a per-pixel alpha surface

surf = pygame.Surface((100, 100), pygame.SRCALPHA)
area_not_to_fill = pygame.Rect(25, 25, 50, 50)

and now I want to fill the surface with a semi-transparent black

surf.fill((0, 0, 0, 128))

but now, all I want is to set a certain part of the surface to be transparent using fill

surf.fill((0, 0, 0, 0), area_not_to_fill, pygame.BLENDMODE_?)

my question is, what blend mode is used to set pixel values instead of doing maths with the previous pixels. Or if that is not possible, then what method can be used to achieve the same effect?

1

There are 1 answers

1
Rabbid76 On BEST ANSWER

The fill function only blends with the background if you set a blend mode. If no blend mode is set, the color is just set. So only specify the area, but not the blend mode:

surf.fill((0, 0, 0, 0), area_not_to_fill)

Minimal example

import pygame

pygame.init()
window = pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()

surf = pygame.Surface((100, 100), pygame.SRCALPHA)
area_not_to_fill = pygame.Rect(25, 25, 50, 50)
surf.fill((0, 0, 0, 128))
surf.fill((0, 0, 0, 0), area_not_to_fill)

run = True
while run:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 
    
    window.fill("white")
    window.blit(surf, surf.get_rect(center = window.get_rect().center))
    pygame.display.flip()

pygame.quit()
exit()