0

I'm trying to use pygame's SysFont to display some text on the screen but I want the background rectangle to be slightly wider than the actual text.

When I use the following code the background seems to start exactly where the first letter starts and finishes exactly where the last letter ends.

font = pygame.font.SysFont("Helvetica", 30)
img = font.render("ABC", True, "white", "blue1")
img_width = img.get_width()
img_height = img.get_height()
screen.blit(img, (200, 200, img_width, img_height))

Is there a way to have some padding to the left and right of the text in the background colour? I thought that perhaps adding something to img_width might help but it didn't.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
RichyRich
  • 31
  • 4

1 Answers1

-1

You need to render the text on Surface larger than the text Surface:

  1. Render the text with a transparent background
  2. Create a Surface larger the the text Surface (see pygame.Rect.inflate)
  3. Fill the Surface with the background color
  4. blit the text in the center of the Surface

Minimal example:

import pygame

pygame.init()
window = pygame.display.set_mode((300, 200))
clock = pygame.time.Clock()

def create_text_box(font, text, text_color, box_color, margin_x, margin_y):
    text_surf = font.render("ABC", True, text_color, "blue1")
    box_surf = pygame.Surface(text_surf.get_rect().inflate(margin_x, margin_y).size)
    box_surf.fill(box_color)
    box_surf.blit(text_surf, text_surf.get_rect(center = box_surf.get_rect().center))
    return box_surf

font = pygame.font.SysFont(None, 100)
text_surf = create_text_box(font, "ABC", "white", "blue1", 10, 0)

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    window.fill(0)
    window.blit(text_surf, text_surf.get_rect(center = window.get_rect().center))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
exit()

See also How to separately change the opacity of a text on a button pygame?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174