python - 如何获得相同比例的缩放输出

标签 python pygame pygame-surface

我正在尝试使用 pygame 制作游戏,但我遇到了一个问题,人们对他们正在使用的分辨率感到恼火,并且无法在不拉伸(stretch)窗口的情况下调整窗口大小。

这是我想要实现的目标的示例图片。

Example Picture of window with black sides as the game ratio is still the same even when stretched

这是我尝试过的。

window.blit(pg.transform.scale(screen, (window.get_size())), (0, 0)) # The game screen stretching

PS:这很难解释,所以我不得不展示一张图片

最佳答案

使用以下算法:

  1. 获取图像的边界矩形,并将矩形的中心设置为目标矩形的中心。
  2. 使用pygame.Rect.fit()调整长宽比矩形的大小并将其移动到目标矩形中。
  3. 使用新矩形的大小来缩放图像。
  4. blit 矩形位置处的图像。
def blit_fit(dest_surf, image, dest_rect):
    image_rect = image.get_rect(center = dest_rect.center)
    fit_rect = image_rect.fit(dest_rect)
    scaled_image = pygame.transform.scale(image, fit_rect.size) 
    dest_surf.blit(scaled_image, fit_rect)

最小示例:

import pygame

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

font = pygame.font.SysFont(None, 100)
image = font.render("Screen", True, (255, 255, 0))
pygame.draw.rect(image, (255, 255, 255), image.get_rect(), 1)

def blit_fit(dest_surf, image, dest_rect):
    image_rect = image.get_rect(center = dest_rect.center)
    fit_rect = image_rect.fit(dest_rect)
    scaled_image = pygame.transform.scale(image, fit_rect.size) 
    dest_surf.blit(scaled_image, fit_rect) 

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

    window.fill(0)
    blit_fit(window, image, window.get_rect())    
    pygame.display.flip()
    clock.tick(100)

pygame.quit()
exit()

关于python - 如何获得相同比例的缩放输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70820655/

相关文章:

python - 在python中嵌入bash

python - 仅评估 tf.Tensor 的非零值

python - 如何获得从图像创建的 pygame 矩形的正确尺寸

python - pygame.camera "livefeed"在 tkinter 窗口内(在 raspbian 上)

python - Pygame:无法打开文件。同一目录

python - Pygame 矩形不会更新

python - Matplotlib错误消息: “TypeError: ' Ellipse' object is not iterable”

python - Pandas 成对算术类似于rolling().corr()

python - 编辑后的操纵杆代码未接收输入

python - pygame中的线条样式