【问题标题】:text being cut in pygame在pygame中被剪切的文本
【发布时间】:2014-04-18 00:55:31
【问题描述】:

我似乎在屏幕上显示文本时遇到问题 代码在屏幕上绘制文本,但“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()

【问题讨论】:

  • 用@jsbueno 所说的更简单的术语来说:blit 接受两个参数,表面和位置,哪个位置是一个元组,而不是元组之外的两个单独的点,所以这意味着screen.blit(bg, 5, 5) 将不起作用,但screen.blit(bg, (5, 5) 会起作用,并将背景从像素点 (5,5) 开始绘制到屏幕上。因此,当您使用 screen.blit(text, self.score_rect, self.score_rect) you are cutting the surface short, but using self.score_rect` 时,它会给出 x、y 坐标以及宽度和高度,示例看起来像 screen.blit(text, (0,0,20,10) 我希望这会有所帮助!
  • @DuhProgrammer13 确实做到了,谢谢 :)

标签: python pygame


【解决方案1】:

好吧 - 它看起来像调用 do blit 的第三个参数,您重复 core_rect` 参数的设计正是为了做到这一点:它选择了一个矩形区域 源图像(在本例中为您渲染的文本)将粘贴到目标(在本例中为屏幕)。

Pygame 中的文本以良好的边距呈现,您根本不需要 source-crop 参数 - 如果您认为需要,您应该传递一组合适的坐标,与呈现的文本相关,而不是矩形屏幕上的目的地坐标。

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

blit() 将一个图像绘制到另一个 blit(source, dest, area=None, special_flags = 0) -> Rect 在此 Surface 上绘制源 Surface。 可以使用 dest 参数定位平局。 Dest 可以是 表示源左上角的坐标对。 一个 Rect 也可以作为目的地和左上角传递 矩形将用作 blit 的位置。的大小 目标矩形不会影响 blit。

也可以传递一个可选的区域矩形。这代表了一个 要绘制的源 Surface 的较小部分。 ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多