Pygame教程系列三:绘制文本篇

【前言】

     前面介绍完了图片的显示与移动视频的播放,接下来介绍一下pygame文本的绘制,pygame绘制文字的流程主要是:加载字体样式库设置文本样式绘制文本到新建的Surface,后面就跟图片的显示过程是一致的了

一、使用系统自带的字体库绘制文本

1、案例效果图

![在这里插入图片描述](https://img-blog.csdnimg.cn/20210129095641706.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjc4ODI2,size_16,color_FFFFFF,t_70

2、案例代码

import pygame
# 标识是否退出循环
exitFlag = False
# 设置画面刷新的帧率,即1s内刷新几次
FPS = 30
# 初始化pygame
pygame.init()
# 设置窗口标题
pygame.display.set_caption("pygame文字绘制教程")
# 设置窗口大小
surface = pygame.display.set_mode((1920,1080),pygame.RESIZABLE)
# 设置icon
icon = pygame.image.load('E:\AS-workspace\pygameTest\drawable\icon.png').convert_alpha()
pygame.display.set_icon(icon)
# 获取游戏时钟
clock = pygame.time.Clock()
# 获取系统所有支持的文字名称
fonts = pygame.font.get_fonts()
print(fonts)
x = 10
y = 20
for f in fonts:
    # 加载系统字体
    font = pygame.font.SysFont(f, 20)
    text = '牛气冲天'
    # 设置是否加粗
    font.bold = True
    # 设置是否倾斜
    font.italic = True
    # 设置是否加下划线
    font.underline = True
    # 绘制文字到一个的Surface中并返回
    textSurface = font.render(text, True, (255, 221, 85))
    # 绘制前先获取文本的宽高
    width, height = font.size(text)
    # 绘制到显示器的surface上
    surface.blit(textSurface, (x, y))
    x += width + 20
    if x > 1800:
        y += 50
        x = 10
# 更新绘制到屏幕上
pygame.display.update()
while not exitFlag:
    clock.tick(FPS)
    for event in pygame.event.get():
        # 点击关闭
        if event.type == pygame.QUIT:
            exitFlag = True



if __name__ == '__main__':
    pass

3、代码详析

1)fonts = pygame.font.get_fonts(),获取系统自带的所有字体的名字,返回的是一个字体集合,比如:

['arial', 'arialblack', 'bahnschrift', 'calibri', 'cambriacambriamath', 'cambria', 'candara', 'comicsansms', 'consolas', 'constantia', 'corbel', 'couriernew', 'ebrima', 'franklingothicmedium', 'gabriola', 'gadugi', 'georgia', 'impact', 'inkfree', 'javanesetext', 'leelawadeeui', 'leelawadeeuisemilight', 'lucidaconsole', 'lucidasans', 'malgungothic', 'malgungothicsemilight', 'microsofthimalaya', 'microsoftjhengheimicrosoftjhengheiui', 'microsoftjhengheimicrosoftjhengheiuibold', 'microsoftjhengheimicrosoftjhengheiuilight', 'microsoftnewtailue', 'microsoftphagspa', 'microsoftsansserif', 'microsofttaile', 'microsoftyaheimicrosoftyaheiui', 'microsoftyaheimicrosoftyaheiuibold', 'microsoftyaheimicrosoftyaheiuilight', 'microsoftyibaiti', 'mingliuextbpmingliuextbmingliuhkscsextb', 'mongolianbaiti', 'msgothicmsuigothicmspgothic', 'mvboli', 'myanmartext', 'nirmalaui', 'nirmalauisemilight', 'palatinolinotype', 'segoemdl2assets', 'segoeprint', 'segoescript', 'segoeui', 'segoeuiblack', 'segoeuiemoji', 'segoeuihistoric', 'segoeuisemibold', 'segoeuisemilight', 'segoeuisymbol', 'simsunnsimsun', 'simsunextb', 'sitkasmallsitkatextsitkasubheadingsitkaheadingsitkadisplaysitkabanner', 'sitkasmallsitkatextboldsitkasubheadingboldsitkaheadingboldsitkadisplayboldsitkabannerbold', 'sitkasmallsitkatextbolditalicsitkasubheadingbolditalicsitkaheadingbolditalicsitkadisplaybolditalicsitkabannerbolditalic', 'sitkasmallsitkatextitalicsitkasubheadingitalicsitkaheadingitalicsitkadisplayitalicsitkabanneritalic', 'sylfaen', 'symbol', 'tahoma', 'timesnewroman', 'trebuchetms', 'verdana', 'webdings', 'wingdings', 'yugothicyugothicuisemiboldyugothicuibold', 'yugothicyugothicuilight', 'yugothicmediumyugothicuiregular', 'yugothicregularyugothicuisemilight', 'dengxian', 'fangsong', 'kaiti', 'simhei', 'holomdl2assets', 'bookshelfsymbol7', 'msreferencespecialty', '方正粗黑宋简体', 'numberonly', 'teamviewer15', 'fzshuti', 'fzyaoti', 'lisu', 'stcaiyun', 'stfangsong', 'sthupo', 'stkaiti', 'stliti', 'stsong', 'stxihei', 'stxingkai', 'stxinwei', 'stzhongsong', 'youyuan', 'haettenschweiler', 'msoutlook', 'bookantiqua', 'centurygothic', 'msreferencesansserif', 'garamond', 'monotypecorsiva', 'agencyfb', 'arialrounded', 'blackadderitc', 'bodoni', 'bodoniblack', 'bodonicondensed', 'bookmanoldstyle', 'bradleyhanditc', 'calisto', 'castellar', 'centuryschoolbook', 'copperplategothic', 'curlz', 'edwardianscriptitc', 'elephant', 'engravers', 'erasitc', 'erasdemiitc', 'erasmediumitc', 'felixtitling', 'forte', 'franklingothicbook', 'franklingothicdemi', 'franklingothicdemicond', 'franklingothicheavy', 'franklingothicmediumcond', 'frenchscript', 'gigi', 'gillsans', 'gillsanscondensed', 'gillsansultra', 'gillsansultracondensed', 'gillsansextcondensed', 'gloucesterextracondensed', 'goudyoldstyle', 'goudystout', 'imprintshadow', 'lucidasansregular', 'lucidasansroman', 'lucidasanstypewriterregular', 'lucidasanstypewriter', 'lucidasanstypewriteroblique', 'maiandragd', 'ocraextended', 'palacescript', 'papyrus', 'perpetua', 'perpetuatitling', 'pristina', 'rage', 'rockwell', 'rockwellcondensed', 'rockwellextra', 'script', 'twcen', 'twcencondensed', 'twcencondensedextra', 'algerian', 'baskervilleoldface', 'bauhaus93', 'bell', 'berlinsansfb', 'berlinsansfbdemi', 'bernardcondensed', 'bodonipostercompressed', 'britannic', 'broadway', 'brushscript', 'californianfb', 'centaur', 'chiller', 'colonna', 'cooperblack', 'footlight', 'freestylescript', 'harlowsolid', 'harrington', 'hightowertext', 'jokerman', 'juiceitc', 'kristenitc', 'kunstlerscript', 'lucidabright', 'lucidacalligraphy', 'lucidafaxregular', 'lucidafax', 'lucidahandwriting', 'magneto', 'maturascriptcapitals', 'mistral', 'modernno20', 'niagaraengraved', 'niagarasolid', 'oldenglishtext', 'onyx', 'parchment', 'playbill', 'poorrichard', 'ravie', 'informalroman', 'showcardgothic', 'snapitc', 'stencil', 'tempussansitc', 'vinerhanditc', 'vivaldi', 'vladimirscript', 'widelatin', 'century', 'wingdings2', 'wingdings3', 'arialms', 'msmincho', 'extra']

2)font = pygame.font.SysFont(f, 20),根据字体名字去系统中查找是否有对应字体,如果有找到,就加载对应的系统字体并返回Font对象;如果没找到,就会尝试去系统查找是否有额外合适的字体可以加载,如果也没有,那么就会去加载pygame自身自带的默认字体库

3)字体样式设置,比如:字体加粗: font.bold = True,字体倾斜: font.italic = True,字体加下划线: font.underline = True

4)textSurface = font.render(text, True, (255, 221, 85)), 绘制指定文本text到surface上,render()方法第2个参数设置是否抗锯齿,这里设置Ture,第3个参数设置字体颜色,假如你想设置字体背景色,可以设置第4个参数: textSurface = font.render(text, True, (255, 221, 85),(255,255,255))

5) width, height = font.size(text),获取指定文本在指定字体样式的情况下,绘制所占的宽、高

6) surface.blit(textSurface, (x, y)),将字体surface绘制到屏幕显示器的surface上

二、使用自定义字体库绘制文本

从上面的效果图可以看出,使用系统自带的字体库绘制文本会存在两个问题:

  • 假如是显示中文,有些字体库是不支持中文的,那么就会显示乱码
  • 假如你指定的字体库名称,在系统中没找到,那么显示出来的字体样式效果也会跟你的预期有所出入

鉴于有以上这些问题,我是比较建议用自定义字体库来绘制文本

1、自定义字体库绘制文本效果图

在这里插入图片描述

2、示例代码

import pygame
# 标识是否退出循环
exitFlag = False
# 设置画面刷新的帧率,即1s内刷新几次
FPS = 30
# 初始化pygame
pygame.init()
# 设置窗口标题
pygame.display.set_caption("pygame文字绘制教程")
# 设置窗口大小
surface = pygame.display.set_mode((1920,1080),pygame.RESIZABLE)
# 设置icon
icon = pygame.image.load('E:\AS-workspace\pygameTest\drawable\icon.png').convert_alpha()
pygame.display.set_icon(icon)
# 获取游戏时钟
clock = pygame.time.Clock()
text = '牛气冲天'
# 字体大小
fontSize = 80
# 字体颜色
fontColor = (255, 221, 85)
# 字体路径
fontPath1 = r'E:\AS-workspace\pygameTest\font\MFQiaoYan-Noncommercial-Regular-2.otf'
# 加载字体
font1 = pygame.font.Font(fontPath1, fontSize)
# 绘制文字到一个的Surface中并返回
textSurface1 = font1.render(text, True, fontColor)

# 字体路径
fontPath2 = r'E:\AS-workspace\pygameTest\font\QianTuXiaoTuTi-2.ttf'
# 加载字体
font2 = pygame.font.Font(fontPath2, fontSize)
# 绘制文字到一个的Surface中并返回
textSurface2 = font2.render(text, True, fontColor)
# 绘制到显示器的surface上
surface.blit(textSurface1, (500,100))
# 绘制到显示器的surface上
surface.blit(textSurface2, (500,200))

# 更新绘制到屏幕上
pygame.display.update()
while not exitFlag:
    clock.tick(FPS)
    for event in pygame.event.get():
        # 点击关闭
        if event.type == pygame.QUIT:
            exitFlag = True



if __name__ == '__main__':
    pass

3、代码详析

1)font1 = pygame.font.Font(fontPath1, fontSize),加载自定义字体跟加载系统字体略有区别:加载系统字体用的是SysFont类,而且是指定字体名字即可,加载自定义字体用的是Font类,需要指定字体样式所在的路径,当然使用Font类,你也可以不指定字体路径,直接传None,那么加载的就是pygame自带的默认字体库,不过pygame自带的字体库是不支持中文的,显示中文是乱码

2)剩下的处理逻辑跟加载系统字体库是一样的,这里就不再重复了

三、使用加强型字体模块pygame.freetype绘制文本

     pygame.freetype 字体模块相比于上述的 pygame.font字体模块,功能更加强大, pygame.freetype可以做到 pygame.font模块所有的功能,还新增旋转竖排摆放文本等,同时还支持加载各种各样的字体库,而且相比于pygame.font底层是SDL ttf实现,pygame.freetype 字体模块底层是FreeType 2,所以不存在向下兼容pygame.font的说法

1、案例效果图展示

在这里插入图片描述

2、案例代码

import pygame.freetype
# 标识是否退出循环
exitFlag = False
# 设置画面刷新的帧率,即1s内刷新几次
FPS = 30
# 初始化pygame
pygame.init()
# 设置窗口标题
pygame.display.set_caption("pygame文字绘制教程")
# 设置窗口大小
surface = pygame.display.set_mode((1920,1080),pygame.RESIZABLE)
# 设置icon
icon = pygame.image.load('E:\AS-workspace\pygameTest\drawable\icon.png').convert_alpha()
pygame.display.set_icon(icon)

# 获取游戏时钟
clock = pygame.time.Clock()
text = '牛气冲天'
# 字体大小
fontSize = 80
# 字体颜色
fontColor = (255, 221, 85)
# 字体路径
fontPath1 = r'E:\AS-workspace\pygameTest\font\MFQiaoYan-Noncommercial-Regular-2.otf'
# 加载字体
font1 = pygame.freetype.Font(fontPath1)
# 绘制文字到一个的Surface中并返回
textSurface1,textSurface1Rect = font1.render(text, fontColor,rotation=30,size=fontSize)

# 字体路径
fontPath2 = r'E:\AS-workspace\pygameTest\font\QianTuXiaoTuTi-2.ttf'
# 加载字体
font2 = pygame.freetype.Font(fontPath2, fontSize)
# 竖排摆放文本
font2.vertical = True
# 加粗
font2.strong = True
# 倾斜
font2.oblique = True
# 加粗程度,默认 0.02778 ( 1/36 ),strong时候为0.08333 ( 1/12 )
font2.strength = 0.03

# 绘制文字到一个的Surface中并返回
textSurface2,textSurface2Rect = font2.render(text, fontColor)
# 绘制到显示器的surface上
surface.blit(textSurface1, (500,100))
# 绘制到显示器的surface上
surface.blit(textSurface2, (1000,100))

# 更新绘制到屏幕上
pygame.display.update()
while not exitFlag:
    clock.tick(FPS)
    for event in pygame.event.get():
        # 点击关闭
        if event.type == pygame.QUIT:
            exitFlag = True



if __name__ == '__main__':
    pass

3、代码详析

1)先导入以下类库

import pygame.freetype

2)font1 = pygame.freetype.Font(fontPath1),加载字体,初始化Font对象,也可以初始化时候设置字体大小:font2 = pygame.freetype.Font(fontPath2, fontSize)

3)设置字体样式,竖排文本:font2.vertical = True,加粗:font2.strong = True,倾斜:font2.oblique = True,还可以设置加粗程度:font2.strength = 0.03(需要配合strong)
4) render(text, fgcolor=None, bgcolor=None, style=STYLE_DEFAULT, rotation=0, size=0) -> (Surface, Rect), 绘制文本到一个新创建的surface对象中返回,可以选择设置字体颜色:fgcolor,背景色:bgcolor, 逆时针旋转的角度:rotation,字体大小:size

5)剩下的就是渲染到屏幕显示器中:surface.blit(textSurface2, (1000,100))

四、总结

     从上面分析可知,pygame的文本绘制比较建议使用pygame.freetype.Font类,因为这个类功能更加强大,可以更灵活地设置字体样式


版权声明:本文为qq_43278826原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。