问题描述
如何使用pygame.transform.scale
重新缩放图像,但保持相同的纵横比?就像我有一个16:9的图像,并且想要在保持相同比例的同时缩放它。我的主要目标是制作图像查看器,因为Windows 10需要永久加载,这是我当前的代码:
import pygame
from sys import argv
from win32api import GetSystemMetrics
pygame.init()
pygame.display.init()
width=GetSystemMetrics(0)*0.9 #Window size a bit smaller than monoitor size
height=GetSystemMetrics(1)*0.8
img=pygame.image.load(argv[-1]) #Get image file opened with it
img=pygame.transform.scale(img,(int(width),int(height))) #Scales image to window size
Main=pygame.display.set_mode((int(width),int(height)))
pygame.display.set_caption(str(argv[-1].split("\\")[-1])) #Set window title as filename
imgrect=img.get_rect()
Main.blit(img,imgrect)
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
exit()
我想问题是我可以调整其大小,但图像变形,或者可以将其显示为图像的宽度和高度,但在保持尺寸不变的情况下,无法缩放到与窗口尺寸一样大的图像宽高比,总会有空白。很抱歉这个模糊的问题,我不知道该怎么解释。
编辑:已修复。如果其他人有同样的问题,我必须将比率标准化,通过将两边除以宽度将其设为1:左右。然后,我将1:something比率乘以窗口的宽度,然后在while循环中,如果图像的宽度大于窗口的宽度,则缩小比例。来源:
import pygame
from sys import argv
from win32api import GetSystemMetrics
pygame.init()
pygame.display.init()
windowwidth=GetSystemMetrics(0)*0.9
windowheight=GetSystemMetrics(1)*0.8
Main=pygame.display.set_mode((int(windowwidth),int(windowheight)))
img=pygame.image.load(argv[-1])
imgratiox=int(1)
imgratioy=int(img.get_height()/img.get_width())
imgwindowwidth=int(windowwidth)
imgwindowheight=int(round(img.get_height()/img.get_width(),2)*windowwidth)
scale=1
while imgwindowheight>windowheight:
imgwindowheight*=scale
imgwindowwidth*=scale
scale-=0.05
img=pygame.transform.scale(img,(int(imgwindowwidth),int(imgwindowheight)))
pygame.display.set_caption(str(argv[-1].split("\\")[-1])+ " Img width:"+str(img.get_width())+" Img height:"+str(img.get_height()))
imgrect=img.get_rect()
Main.blit(img,imgrect)
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
exit()