0

I am trying to draw some text using pygame.freetype.Font however for this font to look good in the context it's in, I want it to have a custom letter-spacing/kerning. By this I mean the ability to change the size of the space between individual letters.

This is the current code I'm using to generate and render the code

d_la_cruz = pygame.freetype.Font(file= _font_dir+"/d-la-cruz-font.ttf")
text_image, text_rect = d_la_cruz.render(text="SQUARES", size=190, fgcolor=Settings.color_menu_title_outline.to_tuple())
text_rect.center = (816, 171)
screen.blit(text_image, text_rect)

Current This is what it currently looks like with that code but the reference I made in gimp looks like this Gimp version.

From what I've found so far, I can't find any easy way to change this and the only other way I can think is individually drawing each letter and manually setting their positions slightly spaced apart. I'd rather not do this for readability and performance so I'd prefer an alternative solution.

Note: I am also using PIL at points in this project so I wouldn't entirely be opposed to solutions using that but I'd rather keep it in pygame if possible

Full Source Code: code

1 Answer 1

0

As far as I know, there is no way to add letter spacing to a text in Pygame. I know you didn't want to display all letters individually, but the following function is very readable and not very performance reducing for short texts. Use it like this:

def render_text_with_letter_spacing(surface, text, font, color, pos, letter_spacing):
    x, y = pos

    for char in text:
        char_surface = font.render(char, True, color)
        surface.blit(char_surface, (x, y))
        x += char_surface.get_width() + letter_spacing

And call it like this:

screen = pygame.display.set_mode((800, 600)) 
font = pygame.font.Font(None, 50)
white = (255, 255, 255)

render_text_with_letter_spacing(screen, "Hello Pygame!", font, white, (100, 250), 20)
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, thanks that looks like my best bet then. I'll give a go at implementing this. I did realise after writing this that in my exact situation I might be able to get away with just using an image instead of having to use pygame but a non-destructive workflow is always preferred so I'll try using this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.