Search code examples
pythontextpygamedraw

can I create a rectangular surface and draw a text over that and blit these objects together in pygame


I need to create a rectangular object and draw a text with respect to the rectangular object and blit these items together in the screen. I am using pygame library to create the game.I am new to this pygame programming. Can someone suggest me method if it is possible?


Solution

  • A text surface is a surface object like any other surface. Render the text:

    font = pygame.font.SysFont(None, 80)
    text_surf = font.render('test text', True, (255, 0, 0))
    

    Create a surface and blit the text surface on it:

    rect_surf = pygame.Surface((400, 100))
    rect_surf.fill((0, 128, 255))
    rect_surf.blit(text_surf, text_surf.get_rect(center = rect_surf.get_rect().center))
    

    Minimal example:

    import pygame
    
    pygame.init()
    window = pygame.display.set_mode((500, 300))
    clock = pygame.time.Clock()
    
    font = pygame.font.SysFont(None, 80)
    text_surf = font.render('test text', True, (255, 0, 0))
    
    rect_surf = pygame.Surface((400, 100))
    rect_surf.fill((0, 128, 255))
    rect_surf.blit(text_surf, text_surf.get_rect(center = rect_surf.get_rect().center))
    
    run = True
    while run:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
    
        window.fill(0)
        window.blit(rect_surf, rect_surf.get_rect(center = window.get_rect().center))
        pygame.display.flip()
    
    pygame.quit()
    exit()
    

    See alos: