Pygame - 带有转义字符或换行符的blitting文本

时间:2015-09-15 15:35:26

标签: python-3.x pygame

您好我正在寻找一些文本到pygame屏幕。我的文字是在推荐一词之后包含/包含换行符。

posX = (self.scrWidth * 1/8)
posY = (self.scrHeight * 1/8)
position = posX, posY
font = pygame.font.SysFont(self.font, self.fontSize)
if text == "INFO":
   text = """If you are learning to play, it is recommended
               you chose your own starting area."""
   label = font.render(text, True, self.fontColour)
   return label, position

return给出了blit的表面和位置。

我尝试使用三重引用方法来包含空格,使用\ n。 我不知道我做错了什么。

2 个答案:

答案 0 :(得分:3)

pygame.font.Font / SysFont()。render()不支持多行文字。

这在文档here中说明。

  

文本只能是一行:不呈现换行符。

解决此问题的一种方法是渲染单行字符串列表。每一行一个,然后将它们一个低于另一个。

示例:

posX = (self.scrWidth * 1/8)
posY = (self.scrHeight * 1/8)
position = posX, posY
font = pygame.font.SysFont(self.font, self.fontSize)
if text == "INFO":
    text = ["If you are learning to play, it is recommended",
            "you chose your own starting area."]
    label = []
    for line in text: 
        label.append(font.render(text, True, self.fontColour))
    return label, position

然后要对图像进行blit,你可以像这样使用另一个for循环:

for line in range(len(label)):
    surface.blit(label(line),(position[0],position[1]+(line*fontsize)+(15*line)))

在blit的Y值中,值为:

position[1]+(line*fontsize)+(15*line)

这正在做的是取位置[0],这是前面的posY变量,并将其用作blit的左上角位置。

然后(line * fontsize)添加到那里。因为for循环使用范围而不是列表项本身,所以行将是1,2,3等等,因此可以添加以将每个连续行直接放在另一行之下。

最后,添加(15 *行)。这就是我们如何获得空间之间的差距。常数,在这种情况下为15,表示边距应该是多少像素。数字越大,差距越大,数字越小,差距越小。添加“线”的原因是为了补偿将上述线向下移动所述量。如果您愿意,可以取走“*行”以查看这将导致行开始重叠。

答案 1 :(得分:1)

这是我在代码中找到并使用的anwser。这会产生一个可以正常使用的文本表面。

class TextRectException:
    def __init__(self, message=None):
            self.message = message

    def __str__(self):
        return self.message


def multiLineSurface(string, font, rect, fontColour, BGColour, justification=0):
    """Returns a surface containing the passed text string, reformatted
    to fit within the given rect, word-wrapping as necessary. The text
    will be anti-aliased.

    Parameters
    ----------
    string - the text you wish to render. \n begins a new line.
    font - a Font object
    rect - a rect style giving the size of the surface requested.
    fontColour - a three-byte tuple of the rgb value of the
             text color. ex (0, 0, 0) = BLACK
    BGColour - a three-byte tuple of the rgb value of the surface.
    justification - 0 (default) left-justified
                1 horizontally centered
                2 right-justified

    Returns
    -------
    Success - a surface object with the text rendered onto it.
    Failure - raises a TextRectException if the text won't fit onto the surface.
    """

    finalLines = []
    requestedLines = string.splitlines()
    # Create a series of lines that will fit on the provided
    # rectangle.
    for requestedLine in requestedLines:
        if font.size(requestedLine)[0] > rect.width:
            words = requestedLine.split(' ')
            # if any of our words are too long to fit, return.
            for word in words:
                if font.size(word)[0] >= rect.width:
                raise TextRectException("The word " + word + " is too long to fit in the rect passed.")
            # Start a new line
            accumulatedLine = ""
            for word in words:
                testLine = accumulatedLine + word + " "
                # Build the line while the words fit.
                if font.size(testLine)[0] < rect.width:
                    accumulatedLine = testLine
                else:
                    finalLines.append(accumulatedLine)
                    accumulatedLine = word + " "
            finalLines.append(accumulatedLine)
        else:
            finalLines.append(requestedLine)

    # Let's try to write the text out on the surface.
    surface = pygame.Surface(rect.size)
    surface.fill(BGColour)
    accumulatedHeight = 0
    for line in finalLines:
        if accumulatedHeight + font.size(line)[1] >= rect.height:
            raise TextRectException("Once word-wrapped, the text string was too tall to fit in the rect.")
        if line != "":
            tempSurface = font.render(line, 1, fontColour)
        if justification == 0:
            surface.blit(tempSurface, (0, accumulatedHeight))
        elif justification == 1:
            surface.blit(tempSurface, ((rect.width - tempSurface.get_width()) / 2, accumulatedHeight))
        elif justification == 2:
            surface.blit(tempSurface, (rect.width - tempSurface.get_width(), accumulatedHeight))
        else:
            raise TextRectException("Invalid justification argument: " + str(justification))
    accumulatedHeight += font.size(line)[1]
    return surface