python
主页 > 脚本 > python >

python在pygame中设置字体并显示中文的介绍

2023-01-27 | 佚名 | 点击:

一、查看可用字体

1

2

import pygame

print(pygame.font.get_fonts())

二、设置字体

1.使用系统字体

1

2

self.font=pygame.font.SysFont(None,48)#None系统默认字体

self.font = pygame.font.SysFont("arial", 16)

2.使用字体文件

字体文件可以外下载

1

self.font = pygame.font.Font("my_font.ttf", 16) #字体,字号

3.设置中文()见前2

1

2

#系统自带

self.font = pygame.font.SysFont("SimHei", 32)  # 显示中文

在网上下载一个中文字体文件,将这个文件与我们的程序放在同一个文件夹,如果是中文的文件名,将它改成英文文件名。例如,下载了迷你简毡笔黑.TTF,将文件名改成了mnjzbh.ttf,并将程序的第一句改成:

1

self.font=pygame.font.Font('mnjzbh.ttf',32) # 显示中文

三、附录:常见系统字体对照表

一般的中文字体名,使用拼音即可,如 仿宋fangsong, 楷体kaiti

新细明体:PMingLiU
细明体:MingLiU
标楷体:DFKai-SB
黑体:SimHei
宋体:SimSun
新宋体:NSimSun
仿宋:FangSong
楷体:KaiTi
仿宋_GB2312:FangSong_GB2312
楷体_GB2312:KaiTi_GB2312
微软正黑体:Microsoft JhengHei
微软雅黑体:Microsoft YaHei

一个应用小例子

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

import pygame.font

 

class BUtton:

    def __init__(self, ai_game, msg):

        """初始化按钮属性"""

        # msg是要在按钮上显示的文本

        self.screen = ai_game.screen

        self.screen_rect = ai_game.screen.get_rect()

 

        # 设置按钮的尺寸和其他属性

        self.width, self.height = 200, 50

        self.buttom_color=(0,255,0)

        self.text_color=(255,255,255)

        self.font=pygame.font.SysFont(None,48)

 

        #创建按钮的rect对象,并使其居中

        self.rect=pygame.Rect(0,0,self.width,self.height)

        self.rect.center=self.screen_rect.center

 

        #按钮的标签只创建一次

        self._pre_msg(msg)

 

    def _pre_msg(self,msg):

        """将msg渲染为图像,并使其在按钮上居中"""

        self.msg_image=self.font.render(msg,True,self.text_color

                                        ,self.buttom_color)

        #布尔实参指定开启还是关闭反锯齿功能,反锯齿让文本的边缘更平滑

        self.msg_image_rect=self.msg_image.get_rect()

        #让图像文本在按钮上居中

        self.msg_image_rect.center=self.rect.center

 

    def draw_button(self):

        """绘制一个用颜色填充的按钮,再绘制文本"""

        self.screen.fill(self.buttom_color,self.rect)

        self.screen.blit(self.msg_image,self.msg_image_rect)

附:在 Pygame 屏幕中添加文字

1

2

3

font = pygame.font.SysFont("freesansbold.ttf", 30)  # 30:font size

text = font.render("content", True, (0,0,0))    # (0,0,0) color of font

self.window.blit(text,(10,10))  # (10,10) rect left top

原文链接:https://blog.csdn.net/huadong_xiaolin/article/details/126257202
相关文章
最新更新