Pygame. How do I resize a surface and keep all objects within proportionate to the new window size?

一笑奈何 提交于 2020-01-23 08:07:28

问题


If I set a pygame window to resizable and then click and drag on the border of the window the window will get larger but nothing blit onto the surface will get larger with it. (Which is understandable) How would I make it so that when I resize a window all blit objects resize with it and fill the window properly?

For example: Say I have a window of 200 x 200 and I blit a button at window_width/2 and window_height/2. The button would be in the center of the window at 100 x 100. Now if I resize the window to 300 x 300 the button stays at 100 x 100 instead of 150 x 150.

I tried messing around with pygame.Surface.get_width ect, but had no luck. Basically I'm trying to resize a program's window and have all blit images stay proportionate.


回答1:


Don't draw on the screen directly, but on another surface. Then scale that other surface to size of the screen and blit it on the screen.

Here's a simple example:

import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((200, 200),HWSURFACE|DOUBLEBUF|RESIZABLE)
fake_screen = screen.copy()
pic = pygame.surface.Surface((50, 50))
pic.fill((255, 100, 200))

while True:
    pygame.event.pump()
    event = pygame.event.wait()
    if event.type == QUIT: pygame.display.quit()
    elif event.type == VIDEORESIZE:
        screen = pygame.display.set_mode(event.dict['size'], HWSURFACE|DOUBLEBUF|RESIZABLE)
        fake_screen.blit(pic, (100, 100))
        screen.blit(pygame.transform.scale(fake_screen, event.dict['size']), (0, 0))
        pygame.display.flip()



回答2:


so without the gui initialization (pygame init, and setmode comands ) in the section where you have existing pygame event get()(which your only allowed one time (or just put in ''for inkey in pygame.event.get(VIDEORESIZE):''( if you want to be redundant))(note you can only use ''for inkey in pygame.event.get(VIDEORESIZE):'' one time per loop because it is really a stack that unstacks when you read the event list so you should really use ''for inkey in pygame.event.get():'' snd put all your key recognission statements after this one occurrance of ''for inkey in pygame.event.get():'':

for inkey in pygame.event.get(VIDEORESIZE)
    if inkey.type == pygame.VIDEORESIZE:
        winwidth,winhight  = inkey.size  # or event.w, event.h
        Window1copy = Window1.copy()# make copy of existing window
        Window1=pygame.display.set_mode((winwidth,winhight),pygame.RESIZABLE) 
        Window1.blit(Window1copy, (0, 0))
        pygame.display.update()



回答3:


Recently with pygame2.0 You can use the SCALED flag



来源:https://stackoverflow.com/questions/34910086/pygame-how-do-i-resize-a-surface-and-keep-all-objects-within-proportionate-to-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!