pygame - 重新缩放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.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()
推荐阅读
- sql - 如何在正则表达式中获取所有组合(无替换的有序采样)
- mysql - MySQL 8 无法启动:插件初始化因错误而中止一般错误
- kubernetes - Istio 入口无法使用无头服务
- java - 删除嵌套的 git 存储库
- vue.js - Webpack 导入的模块不是函数
- excel - 如何根据数据集excel替换单元格字母?
- android - workmanager中android volley的返回响应
- swift - 从 Firebase 分支过滤项目 (SWIFT)
- html - ng-repeat table 多次,每 3 个表在一行中
- css - Java FX 为 2 种语言使用 2 种字体