遊戲界面中文字也是非常常見的元素之一,pygame 專門提供了 Font 模塊來支持文字的顯示。文字在顯示的時候支持系統字體,也支持自定義字體,文字內容可以縮放和旋轉。
如果對pygame感興趣想要系統學習,可以看看我錄的pygame的視頻: https://www.bilibili.com/video/BV1bE411p7Ue
"""__author__ = YuTing"""
import pygame
pygame.init()
window = pygame.display.set_mode((400, 600))
pygame.display.set_caption('顯示文字')
window.fill((255, 255, 255))
# ==============顯示文字============
# 1.創建字體對象(選筆)
# font.SysFont(字體名,字體大小, 是否加粗=False, 是否傾斜=False) - 創建系統字體對象
# font.Font(字體文件路徑, 字體大小)
# font = pygame.font.SysFont('Times', 30)
font = pygame.font.Font('files/t2.TTF', 20)
# 2.通過字體創建文字對象
# 字體對象.render(文字內容,True,文字顏色,背景顏色=None)
text = font.render('hello pygame', True, (0, 0, 255), (0, 255, 0))
# 3.顯示文字
window.blit(text, (0, 0))
# 4.獲取文字內容的寬度和高度
text_w, text_h = text.get_size()
window.blit(text, (400-text_w, 0))
# 5.文字縮放和旋轉
new_text = pygame.transform.rotozoom(text, 45, 1.5)
window.blit(new_text, (100, 200))
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()