Search code examples
fontspygameresizesurfaceblit

Pygame surface resize


When I make window resize, surfaces boundaries not resizing as window do. Text render at main surface in starting window boundaries (600x340). Why? Also a render images (I cut this code part to simplify problem) as background and it render normally according new window's boundaries (I blit direct to main surface(win)). So problem I think is in additional surfaces (text_surf). Why they don't RESIZABLE?

import pygame
import time
pygame.init()

run=True
screen_width=600
screen_height=340
black=(0,0,0)
white=(255,255,255)
font1=pygame.font.SysFont("arial",45)
text_press=font1.render("press any key to play!",0,(100,0,0))
win=pygame.display.set_mode((screen_width,screen_height),pygame.RESIZABLE)
text_surf=pygame.Surface((screen_width,screen_height),pygame.RESIZABLE)
background=pygame.Surface((screen_width,screen_height),pygame.RESIZABLE)

while run==True:
    pygame.time.delay(16)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run=False
        if event.type == pygame.VIDEORESIZE:
            surface = pygame.display.set_mode((event.w, event.h),pygame.RESIZABLE)
            screen_width=event.w
            screen_height=event.h

    win.fill((white))

    background.fill((120,120,100))
    win.blit(background,(0,0))

    text_surf.fill((black))
    text_surf.blit(text_press, (screen_width*0.5-50,screen_height*0.5+100))
    text_surf.set_colorkey(black)
    text_surf.set_alpha(150)
    win.blit(text_surf,(0,0))

    pygame.display.update()
pygame.quit()

Solution

  • The size of text_surf and background doesn't magically change. You need to create a new surface with a new size..
    The pygame.RESIZABLE flag has no effect on pygame.Surface (or it has an effect you do not expect).

    pygame.Surface((screen_width,screen_height),pygame.RESIZABLE)
    

    pygame.RESIZABLE is only intended for use with pygame.display.set_mode. The valid flags for flag argument of the pygame.Surface constructor are pygame.HWSURFACE and pygame.SRCALPHA.

    Create a new Surfaces with the new size when the pygame.VIDEORESIZE event occurs:

    while run==True:
        # [...]
    
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run=False
            if event.type == pygame.VIDEORESIZE:
                surface = pygame.display.set_mode((event.w, event.h),pygame.RESIZABLE)
                screen_width = event.w
                screen_height = event.h
                text_surf = pygame.Surface((screen_width,screen_height))
                background = pygame.Surface((screen_width,screen_height))
    
        # [...]