pygame transparent window alpha?

346 views Asked by At

I was trying to make a pygame window background transparent, I did it with this code:

import win32gui, win32con, win32api
import pygame

pygame.init()
w,h = 400,200
screen = pygame.display.set_mode((w,h))

#font
pygame.font.init()
font1 = pygame.font.SysFont("Arial",128)

# Create layered window
hwnd = pygame.display.get_wm_info()["window"]
win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE,
win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) | win32con.WS_EX_LAYERED)

# Set window transparency color
transp = (255, 0, 128)  # Transparency color
win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(*transp), 0, win32con.LWA_COLORKEY)

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()

    #Drawing text
    screen.fill(transp)
    text = font1.render("hello",True,(255,255,255))
    screen.blit(text, (40,40))

    pygame.display.update()

It works fine until I try to draw images with antialiasing; this is what happens:

The pixels with transparent alpha value become fuchsia :( I've seen that this can be fixed using win32gui.UpdateLayeredWindow() but I didn't find any way to do it in a pygame window. If someone can help me I would be really grateful.

1

There are 1 answers

0
Rabbid76 On

From the comment posted by Exlife (with copy edits):

Do not call SetLayeredWindowAttributes after enabling WS_EX_LAYERED for the window (this will only make the window monochrome transparent so it will be aliased), use UpdateLayeredWindow instead. You need to prepare a memory DC and a 32-bpp bitmap. Update the pixel data of the bitmap (don't use GDI functions, because they delete the alpha channel unconditionally) to update your window. In this case, you also can't add ordinary controls to the window (because the system doesn't draw ordinary controls for a window with alpha blend per pixel), if you want a control, you have to draw it yourself (like DirectUI).