python怎样在pygame中设置字体并显示中文

一、查看可用字体

import pygame
print(pygame.font.get_fonts())

二、设置字体

1.使用系统字体

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

2.使用字体文件

字体文件可以外下载

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

3.设置中文()见前2

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

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

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

一个应用小例子

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)

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇

)">
下一篇>>