简体   繁体   English

python pygame 背景图片随屏幕大小变化

[英]python pygame the background image changes with the screen size

I set screen=p.display.set_mode((width,height),flag,0) as my pygame screen and flag=p.RESIZABLE makes the screen can be stretch.我将screen=p.display.set_mode((width,height),flag,0)为我的 pygame 屏幕, flag=p.RESIZABLE使屏幕可以拉伸。

At this time i load an image as the background, now when i stretch the screen, the background wont change the size by the screen, how can i do it?这时候我加载了一张图片作为背景,现在当我拉伸屏幕时,背景不会随着屏幕改变大小,我该怎么做?

here's the codes:这是代码:

#! /usr/bin/python
import sys
import pygame as p

pic="/home/finals/python/alien/image/muha.png"

def screen_setting(width,height):
    p.init()
    flag=p.RESIZABLE   
    screen=p.display.set_mode((width,height),flag,0)
    bk=p.transform.smoothscale(p.image.load(pic).convert(),(width,height))

    while True:
        for event in p.event.get():
            if event.type == p.QUIT:
                sys.exit()
        screen.blit(bk,(0,0))
        p.display.flip()

screen_setting(1200,800)

You have to implement the VIDEORESIZE event (see pygame.event ).您必须实现VIDEORESIZE事件(请参阅pygame.event )。

When the window is resized, then get the new size of the window from the even attributes:当窗口被调整大小时,然后从偶数属性中获取窗口的新大小:

width, height = event.w, event.h

Create a new Surface associated to the window and scale the background to the new size:创建一个与窗口关联的新 Surface 并将背景缩放到新大小:

def screen_setting(width,height):
    p.init()
    flag = p.RESIZABLE   
    screen=p.display.set_mode((width, height), flag, 0)
    bk_orig = p.image.load(pic).convert()
    bk = p.transform.smoothscale(bk_orig, (width, height))

    while True:
        for event in p.event.get():
            if event.type == p.QUIT:
                sys.exit()
            elif event.type == p.VIDEORESIZE:
                width, height = event.w, event.h
                screen = p.display.set_mode((width, height), flag, 0)
                bk = p.transform.smoothscale(bk_orig, (width, height))

        screen.blit(bk, (0 ,0))
        p.display.flip()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM