pythonpygamecolor-blending

How to get the Difference blending mode?


I'm trying to make a night effect for my game in Pygame. So I'm gonna blit a black image on the screen then, change its blending mode to Difference just like in Photoshop in order to make the screen look darker. However, I still don't know how to do that as I haven't used the blending modes in Pygame yet. Any help ?


Solution

  • The blending mode can be changed by setting the optional special_flags argument of pygame.Surface.blit:

    blit(source, dest, area=None, special_flags=0) -> Rect
    [...]
    New in pygame 1.8: Optional special_flags: BLEND_ADD, BLEND_SUB, BLEND_MULT, BLEND_MIN, BLEND_MAX.
    New in pygame 1.8.1: Optional special_flags: BLEND_RGBA_ADD, BLEND_RGBA_SUB, BLEND_RGBA_MULT, BLEND_RGBA_MIN, BLEND_RGBA_MAX, BLEND_RGB_ADD, BLEND_RGB_SUB, BLEND_RGB_MULT, BLEND_RGB_MIN, BLEND_RGB_MAX.
    New in pygame 1.9.2: Optional special_flags: BLEND_PREMULTIPLIED
    New in pygame 2.0.0: Optional special_flags: BLEND_ALPHA_SDL2 [...]

    e.g.:

    screen.blit(image, (x, y), special_flags = pygame.BLEND_RGBA_SUB)
    

    Unfortunately, Pygame doesn't have a blending mode that gives the absolute difference of 2 images. However it can be achieved with

    MAX(SUB(image1, imgage2), SUB(image2, image1))

    e.g.:

    image1 = pygame.image.load('image2.png')
    image2 = pygame.image.load('image1.png')
    temp_image = image1.copy() 
    temp_image.blit(image2, (0, 0), special_flags = pygame.BLEND_RGBA_SUB)
    final_image = image2.copy() 
    final_image.blit(image1, (0, 0), special_flags = pygame.BLEND_RGBA_SUB)
    final_image.blit(temp_image, (0, 0), special_flags = pygame.BLEND_RGBA_MAX)