【问题标题】:Can you text wrap displayed text in pygame? [duplicate]你可以在pygame中对显示的文本进行文本换行吗? [复制]
【发布时间】:2023-03-15 17:40:01
【问题描述】:

我正在 pygame 中进行一个项目,文本应该显示角色的语音。我已经显示了文本,但它跑出了屏幕。我尝试了一种文本换行的方法,但它没有移动到下一行,所以它只是重叠在同一行上。我不知道是否可以设置某种边界或边框或文本换行。我只能找到 python 的东西,而不是 pygame。

这就是我的文字内容

white = (255,255,255)
def text_objects(text, font):
    textSurface = font.render(text, True, white)
    return textSurface, textSurface.get_rect()
def words(text):
    largeText = pygame.font.Font('freesansbold.ttf', 18)
    TextSurf, TextRect = text_objects((text), largeText)
    TextRect = ((13), (560))
    screen.blit(TextSurf, TextRect)
`   pygame.display.update()

words("This is just filler. Yup, filler to test if this will run off the screen. And apparently \n doesn't start a new line... Doo duh doo. Bum Dum pssst.")

【问题讨论】:

标签: python pygame


【解决方案1】:

我之前的做法是使用 textwrap 将长字符串拆分为适合一行的字符串。然后我用不同的 y 值对它们进行 blit。要拆分文本,您可以这样做:

import textwrap

sentence = "This is just filler. Yup, filler to test if this will run off the screen. And apparently doesn't start a new line... Doo duh doo. Bum Dum pssst."
characters_in_a_line = 60

lines = textwrap.wrap(sentence, characters_in_a_line , break_long_words=False)

它给出了输出:

['This is just filler. Yup, filler to test if this will run', "off the screen. And apparently doesn't start a new line...", 'Doo duh doo. Bum Dum pssst.']

然后我使用一个单独的函数来创建文本矩形,这些矩形被传送到主屏幕:

    def create_text(self, text, font, color, x, y):
        text = font.render(text, True, color)
        rect = text.get_rect()

        rect.topeleft = (x, y)

        self.screen.blit(text, rect)

您只需要知道您的文本有多高,并为 lines 中的每个文本部分发送不同的 y 值。

【讨论】:

    猜你喜欢
    • 2014-01-17
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 2014-06-21
    • 2015-12-11
    • 1970-01-01
    相关资源
    最近更新 更多