pythonpygamedrawrectwindow-resizepygame-surface

How to go about drawing the border of a rectangle in a resizable window using pygame?


I'm trying to create a resizable window in pygame in which a bordered rectangle should be in a fixed proportion with the window.

import pygame,sys 
pygame.init()

win = pygame.display.set_mode((400,400),pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.RESIZABLE)

while True:
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type == pygame.VIDEORESIZE:
            pygame.display.set_mode((event.w,event.h),pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.RESIZABLE)

    win_width,win_height = pygame.display.get_surface().get_size()
    surf = pygame.Surface((round(win_width/2),round(win_height/2)))
    surf.fill((255,255,255))
    win.blit(surf,(win_width/4,win_height/4))
    pygame.draw.rect(surf,(255,0,0),(0,0,surf.get_width(),surf.get_height()),10)
    pygame.display.update()

Thanks in advance!


Solution

  • You draw the rectangle on the white surface (surf). Hence you've to draw it on surf, before you blit surf on win:

    while True:
        # [...]
    
        surf.fill((255,255,255))
        
        pygame.draw.rect(surf,(255,0,0),(0,0,surf.get_width(),surf.get_height()),10)
        win.blit(surf,(win_width/4,win_height/4))
        
        pygame.display.update()   
    

    Alternatively, you can draw a rectangle directly on win:

    while True:
        # [...]
    
        surf.fill((255,255,255))
        rect = win.blit(surf,(win_width/4,win_height/4))
        pygame.draw.rect(win, (255,0,0), rect, 10)
        pygame.display.update()