如何在 Pygame 中将图像缩放到屏幕大小 [英] How to scale images to screen size in Pygame

查看:79
本文介绍了如何在 Pygame 中将图像缩放到屏幕大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何将 pygame 项目中的图像大小缩放到屏幕的分辨率.例如,假设以下场景暂时假设为窗口显示模式;我假设全屏是一样的:

I was wondering how I would go about scaling the size of images in pygame projects to the resolution of the screen. For example, envisage the following scenario assuming windowed display mode for the time being; I assume full screen will be the same:

  • 我有一个 1600x900 背景图片,它当然显示在 1600x900 窗口中

  • I have a 1600x900 background image which of course displays natively in a 1600x900 window

1280x720 窗口中,我显然可以将此图像的矩形缩放到 1280x720

In a 1280x720 window I can obviously just scale this images' rect to 1280x720

但是如果我需要添加,例如 x,y 1440,860(示例尺寸)的 300x300 px 图像大小为适合原始 1600x900 背景吗?当然,对于 1600x900,我当然可以本地使用图像,但是更小/更大的窗口大小呢?

What happens, however if I need to add, say a 300x300 px image at x,y 1440,860 (example sizes) that is sized to fit with the original 1600x900 background? Of course for the 1600x900 I can of course use the image natively but what about the smaller/larger window sizes?

如何将图像缩放到窗口大小,然后相应地定位它们?我想一定有一种非常简单的自动化方法,但现在我无法弄清楚.

How do I scale images to the window size and then position them accordingly? I guess there must be a REALLY easy automated method but right now I can't figure it out.

推荐答案

您可以使用 pygame.transform.scale 缩放图像:

You can scale the image with pygame.transform.scale:

import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))

然后你可以用

rect = picture.get_rect()

并用

rect = rect.move((x, y))
screen.blit(picture, rect)

其中 screen 被设置为类似

screen = pygame.display.set_mode((1600, 900))

<小时>

为了让您的小部件适应各种屏幕尺寸,你可以制作显示可调整大小:

import os
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
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)
        screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
        pygame.display.flip()

这篇关于如何在 Pygame 中将图像缩放到屏幕大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆