gpt4 book ai didi

python - 如何按窗口大小缩放图像?

转载 作者:行者123 更新时间:2023-12-04 07:22:12 25 4
gpt4 key购买 nike

我有一个方形的、不可调整大小的 pygame 窗口,它的大小由监视器大小计算。我有我想要创建的按窗口大小缩放的非方形图像。我希望它由我的 SCREEN_SIZE 变量缩放。这是我的代码,它将图像放在屏幕中间,但如果您更改分辨率,图像将保持相同大小:

import pygame

pygame.init()

# Sets screen size by using your monitors resolution
SCREEN_SIZE = pygame.display.Info().current_h/1.65

screen = pygame.display.set_mode((int(SCREEN_SIZE), int(SCREEN_SIZE)))

gameRunning = True

""" This is the part I need help with. When I run my program the image is the correct
size, but when I change my resolution the image stays the same size and the window's
size changes. I need the image to proportionally scale with the window. """
imgSize = 0.2
img = pygame.image.load(r"location of an image on your PC")
img = pygame.transform.smoothscale(img, (int(img.get_width() * imgSize), int(img.get_height() * imgSize)))

rect = img.get_rect()
rect.center = (screen.get_width()/2, screen.get_height()/2)

while gameRunning == True:
pygame.display.update()

for event in pygame.event.get():
if event.type == pygame.QUIT:
gameRunning = False
pygame.quit()
break

screen.fill((255,255,255))



screen.blit(img, rect)
为了使代码正常工作,您需要为“img”变量添加一个图像位置,并弄乱 imgSize 变量。

最佳答案

比较宽度的比例和高度的比例。按最小比例缩放图像。这甚至适用于非方形窗口分辨率。

ratio_x = screen.get_width() / img.get_width()
ratio_y = screen.get_height() / img.get_height()
scale = min(ratio_x, ratio_y)
img = pygame.transform.smoothscale(img, (int(img.get_width() * scale), int(img.get_height() * scale)))

最小的例子:

import pygame

pygame.init()

screen = pygame.display.set_mode((300, 300))

img = pygame.image.load(r"parrot1.png")
scale = min(screen.get_width() / img.get_width(), screen.get_height() / img.get_height())
img = pygame.transform.smoothscale(img,
(round(img.get_width() * scale), round(img.get_height() * scale)))

rect = img.get_rect(center = screen.get_rect().center)

gameRunning = True
while gameRunning == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameRunning = False

screen.fill((127,127,127))
screen.blit(img, rect)
pygame.display.flip()

pygame.quit()
exit()

关于python - 如何按窗口大小缩放图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68424287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com