文本在pygame中被截断

1 投票
1 回答
733 浏览
提问于 2025-04-18 03:09

我好像在屏幕上显示文字时遇到了一些问题。代码可以在屏幕上画出文字,但“Score”这个词的“S”字母有一半被切掉了。不知道为什么会这样。不过,如果我把代码从“screen.blit(text, self.score_rect, self.score_rect)”改成“screen.blit(text, self.score_rect)”,就没问题了。我想知道这是为什么,以及我该怎么解决这个问题。

谢谢。

这是代码:

class Score(object):
def __init__(self, bg, score=100):
    self.score = score
    self.score_rect = pygame.Rect((10,0), (200,50))
    self.bg = bg

def update(self):
    screen = pygame.display.get_surface() 

    font = pygame.font.Font('data/OpenSans-Light.ttf', 30)
    WHITE = (255, 255, 255)
    BG = (10, 10, 10)

    score = "Score: " + str(self.score)
    text = font.render(score, True, WHITE, BG)
    text.set_colorkey(BG)

    screen.blit(
    self.bg, 
    self.score_rect,
    self.score_rect)

    screen.blit(text, 
    self.score_rect, 
    self.score_rect)


def main():
    pygame.init()

    #initialize pygame
    pygame.init()
    screen = pygame.display.set_mode((640, 480))
    pygame.display.set_caption('Score Window')

    #initialize background
    bg = pygame.Surface((screen.get_size())).convert()
    bg.fill((30, 30, 30))
    screen.blit(bg, (0, 0))

    #initialize scoreboard
    score_board = Score(bg)

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                exit(0)

        score_board.update()
        pygame.display.flip()

1 个回答

0

看起来在调用 blit 的时候,第三个参数 `core_rect` 是专门用来选择源图像上的一个矩形区域的(在这个例子中就是你渲染的文本),然后把这个区域粘贴到目标位置(在这里是屏幕)。

Pygame 中的文本渲染时会有不错的边距,所以你其实不需要使用这个源裁剪参数。如果你觉得需要的话,应该传入适合的坐标,这些坐标应该是在渲染文本内部的,而不是屏幕上目标位置的矩形坐标。

来自 http://www.pygame.org/docs/ref/surface.html#pygame.Surface.blit 的说明:

blit() 是把一幅图像绘制到另一幅图像上,格式是 blit(source, dest, area=None, special_flags=0) -> Rect。这个函数会把源图像绘制到当前图像上。你可以用 dest 参数来设置绘制的位置。dest 可以是表示源图像左上角的坐标对,也可以传入一个矩形,矩形的左上角会作为绘制的位置。目标矩形的大小不会影响绘制的效果。

你还可以传入一个可选的区域矩形,这个矩形表示要绘制的源图像的一个小部分。

...

撰写回答