我有一个方形的、不可调整大小的 pygame 窗口,它的大小由监视器大小计算。我有我想要创建的按窗口大小缩放的非方形图像。我希望它由我的 SCREEN_SIZE 变量缩放。这是我的代码,它将图像放在屏幕中间,但如果您更改分辨率,图像将保持相同大小:
OMP_NUM_THREADS
要使代码正常工作,您需要为“img”变量添加一个图像位置并弄乱 imgSize 变量。
答案 0 :(得分:2)
比较宽度的比例和高度的比例。按最小比例缩放图像。这甚至适用于非方形窗口分辨率。
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()