python中font的用法_如何在pygame中使用pygame.font.font()?

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-17 03:00   41   0

这是改编自我写的一些非常古老的代码:def renderTextCenteredAt(text, font, colour, x, y, screen, allowed_width):

# first, split the text into words

words = text.split()

# now, construct lines out of these words

lines = []

while len(words) > 0:

# get as many words as will fit within allowed_width

line_words = []

while len(words) > 0:

line_words.append(words.pop(0))

fw, fh = font.size(' '.join(line_words + words[:1]))

if fw > allowed_width:

break

# add a line consisting of those words

line = ' '.join(line_words)

lines.append(line)

# now we've split our text into lines that fit into the width, actually

# render them

# we'll render each line below the last, so we need to keep track of

# the culmative height of the lines we've rendered so far

y_offset = 0

for line in lines:

fw, fh = font.size(line)

# (tx, ty) is the top-left of the font surface

tx = x - fw / 2

ty = y + y_offset

font_surface = font.render(line, True, colour)

screen.blit(font_surface, (tx, ty))

y_offset += fh

基本算法是将文本拆分为单词,然后逐字逐行逐字检查结果宽度,并在超出宽度时拆分为新行。在

由于您可以查询呈现文本的宽度,所以您可以确定在何处呈现文本以使其居中。在

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP