首页 > 解决方案 > 重新缩放pygame窗口后如何保留旧屏幕上的内容?

问题描述

我正在尝试制作一个可以调整大小的 pygame 窗口,但在调整大小后只会删除上面的所有内容。所以我自己想了一个解决办法。

pygame.init()
screen=pygame.display.set_mode((640,360),pygame.RESIZABLE)
clock=pygame.time.Clock()
screen.blit(somesurface,(0,0))
pygame.display.flip()
while True:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type==pygame.VIDEORESIZE:
            old=screen
            screen=pygame.display.set_mode(event.size,pygame.RESIZABLE)
            screen.blit(old,(0,0))
            del old
    pygame.display.flip()            

但这不起作用。调整大小后,blitted 表面就消失了。

我正在使用 python 3.8.5 和 pygame 1.9.6

标签: pygame

解决方案


主要问题是pygame.display.set_mode不会创建新的表面对象。它只是重置现有的。当您“保存”旧表面时,您只是在创建对同一对象的另一个引用。如果要保存当前屏幕表面,请使用surface.copy().

我更新了您的代码以复制屏幕,然后以新屏幕为中心重绘保存的屏幕表面。我还打印了前后的屏幕内存地址set_mode。你可以看到屏幕地址没有改变。

import pygame

pygame.init()
screen=pygame.display.set_mode((640,360),pygame.RESIZABLE)
clock=pygame.time.Clock()
somesurface = pygame.Surface((640,360))  # new surface
somesurface.fill((255,255,255))  # fill white
pygame.draw.circle(somesurface,(100,100,255),(320,190),50)  # draw blue circle
screen.blit(somesurface,(0,0)) # draw surface onto screen
pygame.display.flip()
while True:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            exit()
        if event.type==pygame.VIDEORESIZE:
            print(id(screen))  # memory address of screen object
            old=screen.copy()   # copy current screen to temp surface
            screen=pygame.display.set_mode(event.size,pygame.RESIZABLE)  # reset screen
            print(id(screen))  # memory address of 'new' screen object, same address :(
            screen.blit(old,((event.w-old.get_width())//2,(event.h-old.get_height())//2))  # draw back temp surface centered
            del old  # delete temp surface
    pygame.display.flip()

推荐阅读