如何将文本添加到pygame矩形

时间:2013-10-01 13:09:06

标签: python class text pygame drawrectangle

我已经到了在pygame中绘制一个矩形但是我需要能够将“Hello”这样的文本添加到该矩形中。我怎样才能做到这一点? (如果你能解释它,那将非常感激。谢谢你)

这是我的代码:

import pygame
import sys
from pygame.locals import *

white = (255,255,255)
black = (0,0,0)


class Pane(object):
    def __init__(self):

        pygame.init()
        pygame.display.set_caption('Box Test')
        self.screen = pygame.display.set_mode((600,400), 0, 32)
        self.screen.fill((white))
        pygame.display.update()

    def addRect(self):
        self.rect = pygame.draw.rect(self.screen, (black), (175, 75, 200, 100), 2)
        pygame.display.update()

    def addText(self):
        #This is where I want to get the text from

if __name__ == '__main__':
    Pan3 = Pane()
    Pan3.addRect()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit(); sys.exit();

感谢您的时间。

2 个答案:

答案 0 :(得分:6)

首先必须创建一个Font(或SysFont)对象。在此对象上调用render方法将返回带有给定文本的Surface,您可以在屏幕或任何其他Surface上进行blit。

import pygame
import sys
from pygame.locals import *

white = (255,255,255)
black = (0,0,0)


class Pane(object):
    def __init__(self):
        pygame.init()
        self.font = pygame.font.SysFont('Arial', 25)
        pygame.display.set_caption('Box Test')
        self.screen = pygame.display.set_mode((600,400), 0, 32)
        self.screen.fill((white))
        pygame.display.update()


    def addRect(self):
        self.rect = pygame.draw.rect(self.screen, (black), (175, 75, 200, 100), 2)
        pygame.display.update()

    def addText(self):
        self.screen.blit(self.font.render('Hello!', True, (255,0,0)), (200, 100))
        pygame.display.update()

if __name__ == '__main__':
    Pan3 = Pane()
    Pan3.addRect()
    Pan3.addText()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit(); sys.exit();

enter image description here

请注意,您的代码看起来有点奇怪,因为通常您不会事先在主循环中完成所有绘图。此外,当您在程序中大量使用文本时,请考虑缓存Font.render的结果,因为这是一个非常慢的操作。

答案 1 :(得分:0)

嗨! 老实说,有很好的方法可以在当前矩形的任何位置编写文本。 现在我将展示如何轻松做到这一点。


首先我们需要创建 rect 实例的对象:

                rect_obj = pygame.draw.rect(
                    screen,
                    color,
                    <your cords and margin goes here>
                )

现在 rect_objpygame.rect 实例的对象。因此,我们可以自由地使用这种方法进行操作。但是,事先让我们像这样创建我们渲染的文本对象:

                text_surface_object = pygame.font.SysFont(<your font here>, <font size here>).render(
                    <text>, True, <color>
                )

毕竟我们可以自由地使用所有方法,正如我之前提到的: text_rect = text_surface_object.get_rect(center=rect_obj.center)

这段代码是关于什么的? 我们刚刚得到了电流矩形的中心线,如此简单! 现在,你需要像这样 blit 你的屏幕: self.game_screen.blit(text_surface_object, text_rect)


快乐编码! :)

相关问题