4-й параметр font.render
- это необязательный цвет фона текста:
color = (255, 255, 255)
background = (0, 255, 0)
text = font.render(text, True, color, background)
Другой вариант - визуализация текста на поверхности и преобразование формата поверхности в формат альфа-формат пикселя (convert_alpha
):
textSurf = font.render(text, True, color).convert_alpha()
textSize = textSurf.get_size()
Создайте новую поверхность с двойным размером:
bubbleSurf = pygame.Surface((textSize[0]*2., textSize[1]*2))
bubbleRect = bubbleSurf.get_rect()
Заполните поверхность цветом фона пузыря:
bubbleSurf.fill(background)
Перетаскивание текста на поверхность пузыря:
bubbleSurf.blit(textSurf, textSurf.get_rect(center = bubbleRect.center))
Переливание поверхности пузыря на screen
:
bubbleRect.center = (x,y)
screen.blit(bubbleSurf, bubbleRect)
Полная функция text_speech
:
def text_speech(font : str ,size : int,text : str,color,background,x,y, bold : bool):
SCREEN = width, height = 900, 600
font = pygame.font.Font(font,size)
font.set_bold(bold)
textSurf = font.render(text, True, color).convert_alpha()
textSize = textSurf.get_size()
bubbleSurf = pygame.Surface((textSize[0]*2., textSize[1]*2))
bubbleRect = bubbleSurf.get_rect()
bubbleSurf.fill(background)
bubbleSurf.blit(textSurf, textSurf.get_rect(center = bubbleRect.center))
bubbleRect.center = (x,y)
screen.blit(bubbleSurf, bubbleRect)
text_speech('arialnarrow.ttf', 30, 'Hello', (255,255,255), (0,128,0),
width/2, height/2, False)
См. Пример:
import pygame
import pygame.font
pygame.init()
width, height = 400, 300
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
textRect = pygame.Rect(0, 0, 0, 0)
def text_speech(font : str, size : int, text : str,color,background,x,y, bold : bool, bubble: bool):
global textRect
font = pygame.font.SysFont(None, 40)
#font = pygame.font.Font(font,size)
font.set_bold(bold)
textSurf = font.render(text, True, color).convert_alpha()
if bubble:
textSize = textSurf.get_size()
bubbleSurf = pygame.Surface((textSize[0]*2., textSize[1]*2))
textRect = bubbleSurf.get_rect()
bubbleSurf.fill(background)
bubbleSurf.blit(textSurf, textSurf.get_rect(center = textRect.center))
textRect.center = (x,y)
screen.blit(bubbleSurf, textRect)
else:
textRect = textSurf.get_rect()
textRect.center = (x,y)
screen.blit(textSurf, textRect)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
hover = textRect.collidepoint(pygame.mouse.get_pos())
screen.fill((0,0,0))
text_speech('arialnarrow.ttf', 30, 'Hello', (255,255,255), (0, 128, 0),
(width/2), (height/2), False, hover)
pygame.display.flip()