font模块主要用于获取字体Font对象。在pygame中,绘制文字的方法只有一种,就是先获取字体对象,然后字体对象调用render()方法生成一个新的图像(Surface),再将这个图像(Surface)绑定到窗口(Surface)中。
# 获取系统字体的对象的方法
font_name = pygame.font.get_default_font()
font1 = pygame.font.SysFont(font_name, 50)
font_list = pygame.font.get_fonts()
font_path = pygame.font.match_font(font_list[1])
font2 = pygame.font.Font(font_path, 50)
# 获取图片Surface
text_surface1 = font1.render("123", True, (255, 0, 0), (255, 255, 255))
text_surface2 = font1.render("456", True, (255, 0, 0), (255, 255, 255))
# 将图片Surface绑定到窗口Surface
surface.blit(text_surface1, (200, 100))
surface.blit(text_surface2, (400, 100))
下面介绍一下font模块中的函数,如下表:
| 函数 | 描述 |
|---|---|
| pygame.font.init() | 初始化font模块 |
| pygame.font.quit() | 取消初始化font模块 |
| pygame.font.get_init() | 判断font模块是否初始化 |
| pygame.font.get_default_font() | 获得系统字体的文件名 |
| pygame.font.get_fonts() | 获得所有系统字体文件名的列表 |
| pygame.font.match_font() | 根据文件名查找字体的路径 |
| pygame.font.SysFont() | 根据字体的名称获得对应的Font对象 |
| pygame.font.Font() | 根据字体的路径或者字体的文件名获得对应的Font对象 |
对于一个Font对象,有下列方法:
| 函数 | 描述 |
|---|---|
| pygame.font.Font.bold | Gets or sets whether the font should be rendered in (faked) bold. |
| pygame.font.Font.italic | Gets or sets whether the font should be rendered in (faked) italics. |
| pygame.font.Font.underline | Gets or sets whether the font should be rendered with an underline. |
| pygame.font.Font.render | draw text on a new Surface |
| pygame.font.Font.size | determine the amount of space needed to render text |
| pygame.font.Font.set_underline | control if text is rendered with an underline |
| pygame.font.Font.get_underline | check if text will be rendered with an underline |
| pygame.font.Font.set_bold | enable fake rendering of bold text |
| pygame.font.Font.get_bold | check if text will be rendered bold |
| pygame.font.Font.set_italic | enable fake rendering of italic text |
| pygame.font.Font.metrics | gets the metrics for each character in the passed string |
| pygame.font.Font.get_italic | check if the text will be rendered italic |
| pygame.font.Font.get_linesize | get the line space of the font text |
| pygame.font.Font.get_height | get the height of the font |
| pygame.font.Font.get_ascent | get the ascent of the font |
| pygame.font.Font.get_descent | get the descent of the font |
总结一下,font模块中比较常用的方法有:
pygame.font.Font(filename, size) pygame.font.Font(pathlib.Path, size)filename:字体文件的文件名;
pathlib.Path: 字体文件的路径;
size:字体的高height,单位为像素;
text:要显示的文字;
antialias: 是否抗锯齿;
color:字体颜色;
background:背景颜色(可选参数)



