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

丶灬走出姿态 提交于 2021-01-07 03:23:35

问题


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?


回答1:


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:

  • Python display text with font & color?
  • Python - Pygame - rendering translucent text
  • python library pygame: centering text


来源:https://stackoverflow.com/questions/64956732/can-i-create-a-rectangular-surface-and-draw-a-text-over-that-and-blit-these-obje

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!