国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Pygame’s Font text and 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: %%PRE_BLOCK_2%%
Home Backend Development Python Tutorial Python's Pygame Font module - how to use text and fonts?

Python's Pygame Font module - how to use text and fonts?

Apr 23, 2023 pm 11:19 PM
python pygame font

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:

Cancel initialization of the font module##pygame.font.get_init() pygame.font.get_default_font() pygame.font.get_fonts() pygame.font.match_font() pygame.font.SysFont() pygame.font.Font()
Name Description
pygame.font.init() Initialize the font module
##pygame.font.quit()
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
The Font

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)

font.SysFont()

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.

  • size
  • : Indicates the size of the font;

  • bold
  • : Whether the font is bold;

  • italic
  • : Whether the font is italic.

    Usage examples are as follows:
  • print("獲取系統(tǒng)中所有可用字體",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)

The parameter description is as follows:

    filename
  • : string format, indicating the path of the font file;

  • size
  • : Set the font size.

    Usage example is as follows:
  • f = pygame.font.Font('C:/Users/Administrator/Desktop/willhar_.ttf',50)
Loaded a font file from the desktop to create a font object and set the font size to 50. Note that the above font files are downloaded from the Internet, you can also download them by clicking on the URL), or use the font files in the system library.

Font object methods

Pygame provides some common methods for handling font objects, as follows:

NameDescription##pygame.font.Font.render() pygame.font.Font.size() Whether to draw an underline for the text contentCheck whether the text is underlinedStart bold font rendering##pygame.font.Font.get_bold() Check whether the text is rendered in boldpygame.font.Font.set_italic() Start italic rendering pygame.font.Font.metrics() Get the detailed parameters of each character in the stringpygame.font.Font.get_italic() Check whether the text is rendered in italicspygame.font .Font.get_linesize() Get the line height of font textpygame.font.Font.get_height() Get the height of the fontGet the distance from the top of the font to the baselineGet the distance from the bottom of the font to the baseline

    This function creates a rendered text Surface object
    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_ascent()
    pygame.font.Font.get_descent()
    <blockquote><p>使用上述方法,我們可以非常方便地對字體進(jìn)行渲染,或者獲取字體的相關(guān)信息,比如字體的高度、是否是粗體、斜體等信息。</p></blockquote><p>上述方法中使用最多要數(shù)第一個(gè)方法,它是繪制文本內(nèi)容的關(guān)鍵方法,其語法格式如下:</p><pre class='brush:php;toolbar:false;'>render(text, antialias, color, background=None)</pre><p>參數(shù)說明如下:</p><ul class=" list-paddingleft-2"><li><p><code>text : 要繪制的文本內(nèi)容

  1. antialias : 布爾值參數(shù),是否是平滑字體(抗鋸齒)。

  2. color : 設(shè)置字體顏色;

  3. background : 可選參數(shù),默認(rèn)為 None,該參數(shù)用來設(shè)置字體的背景顏色。

  4. 下面看一組簡單的示例:

    import sys
    import pygame
    
    # 初始化
    pygame.init()
    screen = pygame.display.set_mode((600, 400))
    # 填充主窗口的背景顏色
    screen.fill((20, 90, 50))
    # 設(shè)置窗口標(biāo)題
    pygame.display.set_caption(&#39;Python自學(xué)網(wǎng)&#39;)
    # 字體文件路徑 C:/Windows/Fonts/simhei.ttf
    f = pygame.font.Font(&#39;C:/Windows/Fonts/simhei.ttf&#39;, 50)
    # render(text, antialias, color, background=None) -> Surface
    text = f.render("網(wǎng)址:python.net", True, (255, 0, 0), (255, 255, 255))
    # 獲得顯示對象的 rect區(qū)域大小
    textRect = text.get_rect()
    # 設(shè)置顯示對象居中
    textRect.center = (300, 200)
    screen.blit(text, textRect)
    while True:
        # 循環(huán)獲取事件,監(jiān)聽事件
        for event in pygame.event.get():
            # 判斷用戶是否點(diǎn)了關(guān)閉按鈕
            if event.type == pygame.QUIT:
                # 卸載所有pygame模塊
                pygame.quit()
                # 終止程序
                sys.exit()
        pygame.display.flip()  # 更新屏幕內(nèi)容

    除了使用上述方法之外,Pygame 為了增強(qiáng)字體模塊的功能,在新的版本中又加入了另外一個(gè)字體模塊,它就是 Freetype 模塊。該模塊屬于 Pygame 的高級模塊, 它能夠完全可以取代 Font 模塊,并且在 Font 模塊的基礎(chǔ)上又添加了許多新功能,比如調(diào)整字符間距離,字體垂直模式以及逆時(shí)針旋轉(zhuǎn)文本等(詳情可閱讀官方文檔)。

    如果想 Freetype 模塊,必須使用以下方式導(dǎo)包:

    import pygame.freetype

    下面使用 Freetype 模塊來繪制文本內(nèi)容,代碼如下:

    import sys, pygame
    import pygame.freetype
    
    pygame.init()
    # 設(shè)置位置變量
    pos = [180, 50]
    # 設(shè)置顏色變量
    GOLD = 255, 251, 0
    BLACK = 0, 0, 0
    screen = pygame.display.set_mode((600, 400))
    pygame.display.set_caption("Python自學(xué)網(wǎng)")
    f1 = pygame.freetype.Font("C:/Users/Administrator/Desktop/willhar_.ttf", 45)
    # 注意,這里使用render_to() 來繪制文本內(nèi)容,與render 相比,該方法無返回值
    # 參數(shù)說明:
    # pos 繪制文本開始的位置,fgcolor表示前景色,bgcolor表示背景色,rotation表示文本旋轉(zhuǎn)的角度
    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()

    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

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    How to handle API authentication in Python How to handle API authentication in Python Jul 13, 2025 am 02:22 AM

    The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.

    How to test an API with Python How to test an API with Python Jul 12, 2025 am 02:47 AM

    To test the API, you need to use Python's Requests library. The steps are to install the library, send requests, verify responses, set timeouts and retry. First, install the library through pipinstallrequests; then use requests.get() or requests.post() and other methods to send GET or POST requests; then check response.status_code and response.json() to ensure that the return result is in compliance with expectations; finally, add timeout parameters to set the timeout time, and combine the retrying library to achieve automatic retry to enhance stability.

    Python variable scope in functions Python variable scope in functions Jul 12, 2025 am 02:49 AM

    In Python, variables defined inside a function are local variables and are only valid within the function; externally defined are global variables that can be read anywhere. 1. Local variables are destroyed as the function is executed; 2. The function can access global variables but cannot be modified directly, so the global keyword is required; 3. If you want to modify outer function variables in nested functions, you need to use the nonlocal keyword; 4. Variables with the same name do not affect each other in different scopes; 5. Global must be declared when modifying global variables, otherwise UnboundLocalError error will be raised. Understanding these rules helps avoid bugs and write more reliable functions.

    Python FastAPI tutorial Python FastAPI tutorial Jul 12, 2025 am 02:42 AM

    To create modern and efficient APIs using Python, FastAPI is recommended; it is based on standard Python type prompts and can automatically generate documents, with excellent performance. After installing FastAPI and ASGI server uvicorn, you can write interface code. By defining routes, writing processing functions, and returning data, APIs can be quickly built. FastAPI supports a variety of HTTP methods and provides automatically generated SwaggerUI and ReDoc documentation systems. URL parameters can be captured through path definition, while query parameters can be implemented by setting default values ??for function parameters. The rational use of Pydantic models can help improve development efficiency and accuracy.

    Python for loop with timeout Python for loop with timeout Jul 12, 2025 am 02:17 AM

    Add timeout control to Python's for loop. 1. You can record the start time with the time module, and judge whether it is timed out in each iteration and use break to jump out of the loop; 2. For polling class tasks, you can use the while loop to match time judgment, and add sleep to avoid CPU fullness; 3. Advanced methods can consider threading or signal to achieve more precise control, but the complexity is high, and it is not recommended for beginners to choose; summary key points: manual time judgment is the basic solution, while is more suitable for time-limited waiting class tasks, sleep is indispensable, and advanced methods are suitable for specific scenarios.

    How to parse large JSON files in Python? How to parse large JSON files in Python? Jul 13, 2025 am 01:46 AM

    How to efficiently handle large JSON files in Python? 1. Use the ijson library to stream and avoid memory overflow through item-by-item parsing; 2. If it is in JSONLines format, you can read it line by line and process it with json.loads(); 3. Or split the large file into small pieces and then process it separately. These methods effectively solve the memory limitation problem and are suitable for different scenarios.

    Python for loop over a tuple Python for loop over a tuple Jul 13, 2025 am 02:55 AM

    In Python, the method of traversing tuples with for loops includes directly iterating over elements, getting indexes and elements at the same time, and processing nested tuples. 1. Use the for loop directly to access each element in sequence without managing the index; 2. Use enumerate() to get the index and value at the same time. The default index is 0, and the start parameter can also be specified; 3. Nested tuples can be unpacked in the loop, but it is necessary to ensure that the subtuple structure is consistent, otherwise an unpacking error will be raised; in addition, the tuple is immutable and the content cannot be modified in the loop. Unwanted values can be ignored by \_. It is recommended to check whether the tuple is empty before traversing to avoid errors.

    What are python default arguments and their potential issues? What are python default arguments and their potential issues? Jul 12, 2025 am 02:39 AM

    Python default parameters are evaluated and fixed values ??when the function is defined, which can cause unexpected problems. Using variable objects such as lists as default parameters will retain modifications, and it is recommended to use None instead; the default parameter scope is the environment variable when defined, and subsequent variable changes will not affect their value; avoid relying on default parameters to save state, and class encapsulation state should be used to ensure function consistency.

    See all articles