1

I have read this post about centering text: Pygame - How to Center Text

However instead of importing text from a file:

font = pygame.font.Font("example_font.tff", 25)

I want to use a font from the users system

font = pygame.freetype.SysFont("comicsansms", 0)

using the freetype module as I think it makes rendering to various sizes easier (like when the user resizes the window)
font.render_to(surface, pos, ..., size=int(surface.get_height()/2))

Im not sure how to set a value for pos where the text will be shown in the center of the surface, as I can't .get_rect() or anything to get the dimensions of the text

Possible solutions?
Getting the dimensions of the text
Using System Fonts with pygame.font.Font()

Thanks!

k-shar
  • 79
  • 1
  • 8
  • 1
    render the font first then adjust the position after. So use `txt = font.render(text, antialiasing, color) -> Surface` and then `text_rect = txt.get_rect(center=centered_pos)`. this creates a surface in memory and you will still need to blit it. In order to get the size of a loaded font just use `font.size("txt")` – TheLazyScripter Dec 13 '20 at 16:52
  • I don't know how to calculate the position "pos" that it needs to be rendered to, because I'm not sure how to get the dimensions of the rendered text – k-shar Dec 13 '20 at 16:54

1 Answers1

2

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()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • Im not using freetype.Font, im using freetype.SysFont and I don't believe that SysFont has the method .get_rect() – k-shar Dec 13 '20 at 17:01
  • @k-shar See the documentation: https://www.pygame.org/docs/ref/freetype.html#pygame.freetype.Font.get_rect. I've provided the link in the answer. You just have to read the answer. – Rabbid76 Dec 13 '20 at 17:02
  • 1
    @k-shar `freetype.Font` and `freetype.SysFont` have the same interface – Rabbid76 Dec 13 '20 at 17:08