根据屏幕比例调整大小

时间:2019-03-27 16:33:31

标签: python pygame

我对pygame有问题。具体来说,我一直在坚持如何按比例调整文本的大小(窗口可调整大小并带有图片)。

这是我的代码。

import pygame
from pygame.locals import *
import numpy as np
import matplotlib.pyplot as plt
import argparse
import threading, os, sys, time

pygame.init()
pygame.display.set_caption("AI Battlehip Game")
FPS = pygame.time.Clock()

red = (255,0,0)

screen = pygame.display.set_mode((1200,700), HWSURFACE|DOUBLEBUF|RESIZABLE)
add_screen = screen.copy()
back_end_image_set = pygame.image.load(r'/Users/User1/Desktop/Project work/images/backgroundimage1.jpg') 
screen.blit(pygame.transform.scale(back_end_image_set, (1200,700)), (0,0))
pygame.display.flip()


myFont = pygame.font.SysFont("monospace", 300)
label = myFont.render("Check 1", 40, (red))
add_screen.blit(pygame.transform.scale(label, (700, 500)), (0,0))

FPS.tick(60)

try:                                                   
    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(back_end_image_set, event.dict['size']), (0,0))
            pygame.display.flip()
except:
    raise

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

首先存储表面的原始大小:

original_size = (1200,700)
screen = pygame.display.set_mode(original_size, HWSURFACE|DOUBLEBUF|RESIZABLE)

那么您有2个选择。

选项1:

使用pygame.font并将文本渲染到表面上

myFont = pygame.font.SysFont("monospace", 300)
label = myFont.render("Check 1", 40, (red))

通过新窗口大小和原始窗口大小的比例缩放文本表面,并将其blit缩放到表面:

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)

    new_size = event.dict['size']
    screen.blit(pygame.transform.scale(back_end_image_set, new_size), (0,0))

    label_w = label.get_width() * new_size[0] // original_size[0]
    label_h = label.get_height() * new_size[1] // original_size[1]

    screen.blit(pygame.transform.scale(label, (label_w, label_h)), (0,0))
    pygame.display.flip()

选项2:

使用pygame.freetype

import pygame.freetype

myFont = pygame.freetype.SysFont('monospace', 30)

计算文本区域的缩放大小,并将其直接呈现到调整大小的屏幕上。请注意,文本是按新窗口宽度和原始窗口宽度的比例缩放的。 此实现保留了文本的宽度和高度的比例,并且不会拉伸或压缩文本:

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)

    new_size = event.dict['size']
    screen.blit(pygame.transform.scale(back_end_image_set, new_size), (0,0))

    myFont.render_to(screen, (0, 0), "Check 1", fgcolor=red, size = 300 * new_size[0] // original_size[0])
    pygame.display.flip()