Pygame 表面调整大小

问题描述

当我调整窗口大小时,表面边界不会像窗口那样调整大小。在起始窗口边界 (600x340) 的主表面上呈现文本。为什么?还有一个渲染图像(我剪切了这个代码部分以简化问题)作为背景,它根据新窗口的边界正常渲染(我直接 blit 到主表面(win))。所以我认为问题在于附加表面(text_surf)。为什么它们不能调整大小?

import pygame
import time
pygame.init()

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

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

解决方法

text_surfbackground 的大小不会神奇地改变。您需要创建一个具有新尺寸的新表面..
pygame.RESIZABLE 标志对 pygame.Surface 没有影响(或者它有您意想不到的影响)。

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

pygame.RESIZABLE 仅适用于 pygame.display.set_modepygame.Surface 构造函数的标志参数的有效标志是 pygame.HWSURFACEpygame.SRCALPHA

pygame.VIDEORESIZE 事件发生时,使用新的尺寸创建一个新的 Surfaces:

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))

    # [...]