gpt4 book ai didi

python - 如何将文字放置到指定位置?

转载 作者:行者123 更新时间:2023-12-01 08:08:40 24 4
gpt4 key购买 nike

我坚持如何将文本放置在特定坐标上(包括可调整大小的窗口和背景图片)。这是我的代码:

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")

original_size = (1200,700)

FPS = pygame.time.Clock()

red = (255,0,0)

screen = pygame.display.set_mode(original_size, HWSURFACE|DOUBLEBUF|RESIZABLE)
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, original_size), (0,0))
pygame.display.flip()


myFont = pygame.font.SysFont('freesansbold.ttf', 60)
label = myFont.render('Check 1', 1, (red))

pos_W = (1200 - label.get_width())//2
pos_H = (700 - label.get_height())//2

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)
new_size = event.dict['size']
screen.blit(pygame.transform.scale(back_end_image_set, new_size), (0,0))
label_W = pos_W * new_size[0] // original_size[0]
label_H = pos_H * new_size[1] // original_size[1]
screen.blit(pygame.transform.scale(label, (label_W, label_H)), (0,0))
pygame.display.flip()
except:
raise

任何帮助将不胜感激。非常感谢!

最佳答案

您必须缩放文本表面(标签)的位置和大小:

label_W = label.get_width() * new_size[0] // original_size[0]
label_H = label.get_height() * new_size[1] // original_size[1]
label_X = pos_W * new_size[0] // original_size[0]
label_Y = pos_H * new_size[1] // original_size[1]
screen.blit(pygame.transform.scale(label, (label_W, label_H)), (label_X, label_Y))

请注意,调整线性大小会沿 x 和 y 轴缩放窗口。 x 轴和 y 轴的比例因子可以应用于表面上的每个点或矢量。矩形的位置以与其大小相同的比例变化:

scale_x, scale_y = (new_size[0] / original_size[0], new_size[1] / original_size[1])

label_size = (int(label.get_width() * scale_x), int(label.get_height() * scale_y))
label_pos = (int(pos_W * scale_x), int(pos_H * scale_y))

screen.blit(pygame.transform.scale(label, label_size), label_pos)

关于python - 如何将文字放置到指定位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55403164/

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