Pygame: Centering text system font text

前端 未结 1 1708
自闭症患者
自闭症患者 2021-01-27 04:39

I have read this post about centering text: python library pygame: centering text

However instead of importing text from a file:

font = pyga

1条回答
  •  北恋
    北恋 (楼主)
    2021-01-27 05:15

    Use pygame.freetype.Font.get_rect to get a pygame.Rect object with the size of the text. Note, freetype.Font and freetype.SysFont have the same interface:

    text = "Hello World"
    text_size = 50
    
    text_rect = font.get_rect(text, size = text_size)
    text_rect.center = surface.get_rect().center 
    
    font.render_to(surface, text_rect, text, color, size = text_size)
    

    Minimal examaple:

    import pygame
    import pygame.freetype
    
    pygame.init()
    window = pygame.display.set_mode((400, 200))
    
    def drawTextCentered(surface, text, text_size, color):
        text_rect = font.get_rect(text, size = 50)
        text_rect.center = surface.get_rect().center 
        font.render_to(surface, text_rect, text, color, size = 50)  
    
    font = pygame.freetype.SysFont("comicsansms", 0) 
    
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
    
        window.fill(0)
        drawTextCentered(window, "Hello World", 50, (255, 0, 0))  
        pygame.display.flip()
    
    pygame.quit()
    exit()
    

    0 讨论(0)
提交回复
热议问题