When we want to introduce a cooler font into the game but it does not exist in the system, we can An alternative method is to load font files externally to draw text. The syntax format is as follows:
my_font = pygame.font.Font(filename, size)
Python's Pygame Font module - how to use text and fonts?
Pygame’s Font text and font
Pygame creates a font object through the pygame.font
module to achieve the purpose of drawing text.
The common methods of this module are as follows:
Name | Description |
---|---|
pygame.font.init() |
Initialize the font module |
##pygame.font.quit()
| Cancel initialization of the font module|
Check whether the font module has been initialized and return a Boolean value. |
|
Get the file name of the default font. Return the file name of the font in the system |
|
Get all available fonts, the return value is all available Font list |
|
Matches font files from the system’s font library, and the return value is the complete font File path |
|
Create a Font object from the system’s font library |
|
Create a Font object from a font file |
module provides two methods for creating font (Font) objects, namely:
- SysFont
(Load font files from the system to create font objects )
- Font
(Create font object through file path)
Use the following method to load fonts directly from the system:
pygame.font.SysFont(name, size, bold=False, italic=False)
Parameter description is as follows:
- ##name
- : List parameter Value, indicating the name of the font to be loaded from the system. It will be searched in the order of the elements in the list. If there is no font in the list in the system, Pygame's default font will be used.
- : Indicates the size of the font;
- : Whether the font is bold;
- : Whether the font is italic.
Usage examples are as follows:
print("获取系统中所有可用字体",pygame.font.get_fonts()) my_font = pygame.font.SysFont(['方正粗黑宋简体','microsoftsansserif'],50)
The above method will give priority to "Founder Bold Black Song Simplified".
font.Font()
When we want to introduce a cooler font into the game but it does not exist in the system, we can An alternative method is to load font files externally to draw text. The syntax format is as follows:
my_font = pygame.font.Font(filename, size)
Copy after login
The parameter description is as follows: my_font = pygame.font.Font(filename, size)
- filename
- : string format, indicating the path of the font file;
- : Set the font size.
Usage example is as follows:
f = pygame.font.Font('C:/Users/Administrator/Desktop/willhar_.ttf',50)
This function creates a rendered text Surface object
| pygame.font.Font.size() |
This function returns the size required to render text. The return value is a One-tuple (width,height)
| ##pygame.font.Font.set_underline() |
| pygame.font.Font.get_underline() |
| pygame.font.Font.set_bold() |
| ##pygame.font.Font.get_bold() |
| pygame.font.Font.set_italic() |
| pygame.font.Font.metrics() |
| pygame.font.Font.get_italic() |
| pygame.font .Font.get_linesize() |
| pygame.font.Font.get_height() |
##pygame.font.Font.get_ascent() | Get the distance from the top of the font to the baseline |
pygame.font.Font.get_descent() | Get the distance from the bottom of the font to the baseline |
<blockquote><p>使用上述方法,我们可以非常方便地对字体进行渲染,或者获取字体的相关信息,比如字体的高度、是否是粗体、斜体等信息。</p></blockquote><p>上述方法中使用最多要数第一个方法,它是绘制文本内容的关键方法,其语法格式如下:</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>render(text, antialias, color, background=None)</pre><div class="contentsignin">Copy after login</div></div><p>参数说明如下:</p><ul class=" list-paddingleft-2"><li><p><code>text : 要绘制的文本内容
下面看一组简单的示例: import sys import pygame # 初始化 pygame.init() screen = pygame.display.set_mode((600, 400)) # 填充主窗口的背景颜色 screen.fill((20, 90, 50)) # 设置窗口标题 pygame.display.set_caption('Python自学网') # 字体文件路径 C:/Windows/Fonts/simhei.ttf f = pygame.font.Font('C:/Windows/Fonts/simhei.ttf', 50) # render(text, antialias, color, background=None) -> Surface text = f.render("网址:python.net", True, (255, 0, 0), (255, 255, 255)) # 获得显示对象的 rect区域大小 textRect = text.get_rect() # 设置显示对象居中 textRect.center = (300, 200) screen.blit(text, textRect) while True: # 循环获取事件,监听事件 for event in pygame.event.get(): # 判断用户是否点了关闭按钮 if event.type == pygame.QUIT: # 卸载所有pygame模块 pygame.quit() # 终止程序 sys.exit() pygame.display.flip() # 更新屏幕内容 Copy after login 除了使用上述方法之外,Pygame 为了增强字体模块的功能,在新的版本中又加入了另外一个字体模块,它就是 Freetype 模块。该模块属于 Pygame 的高级模块, 它能够完全可以取代 Font 模块,并且在 Font 模块的基础上又添加了许多新功能,比如调整字符间距离,字体垂直模式以及逆时针旋转文本等(详情可阅读官方文档)。 如果想 Freetype 模块,必须使用以下方式导包: import pygame.freetype Copy after login 下面使用 Freetype 模块来绘制文本内容,代码如下: import sys, pygame import pygame.freetype pygame.init() # 设置位置变量 pos = [180, 50] # 设置颜色变量 GOLD = 255, 251, 0 BLACK = 0, 0, 0 screen = pygame.display.set_mode((600, 400)) pygame.display.set_caption("Python自学网") f1 = pygame.freetype.Font("C:/Users/Administrator/Desktop/willhar_.ttf", 45) # 注意,这里使用render_to() 来绘制文本内容,与render 相比,该方法无返回值 # 参数说明: # pos 绘制文本开始的位置,fgcolor表示前景色,bgcolor表示背景色,rotation表示文本旋转的角度 freeRect = f1.render_to(screen, pos, "I love python.net", fgcolor=GOLD, bgcolor=BLACK, rotation=35) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() pygame.display.update() Copy after login The above is the detailed content of Python's Pygame Font module - how to use text and fonts?. For more information, please follow other related articles on the PHP Chinese website! Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
![]() Hot AI Tools![]() Undresser.AI UndressAI-powered app for creating realistic nude photos ![]() AI Clothes RemoverOnline AI tool for removing clothes from photos. ![]() Undress AI ToolUndress images for free ![]() Clothoff.ioAI clothes remover ![]() Video Face SwapSwap faces in any video effortlessly with our completely free AI face swap tool! ![]() Hot Article
Assassin's Creed Shadows: Seashell Riddle Solution
4 weeks ago
By DDD
What's New in Windows 11 KB5054979 & How to Fix Update Issues
3 weeks ago
By DDD
Where to find the Crane Control Keycard in Atomfall
4 weeks ago
By DDD
Roblox: Dead Rails - How To Complete Every Challenge
1 months ago
By DDD
Atomfall guide: item locations, quest guides, and tips
1 months ago
By DDD
![]() Hot Tools![]() Notepad++7.3.1Easy-to-use and free code editor ![]() SublimeText3 Chinese versionChinese version, very easy to use ![]() Zend Studio 13.0.1Powerful PHP integrated development environment ![]() Dreamweaver CS6Visual web development tools ![]() SublimeText3 Mac versionGod-level code editing software (SublimeText3) ![]() Hot Topics![]() PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning. ![]() PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem. ![]() Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming. ![]() VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security. ![]() VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time. ![]() PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields. ![]() In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency. ![]() VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software. ![]() |