You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何修复Pygame中阿拉伯/波斯文本与字体显示异常问题?

修复Pygame中阿拉伯文本渲染分隔问题

这个问题的根源在于阿拉伯语是**从右到左(RTL)**的连写文字系统,而Pygame 1.x和早期2.x版本的font.render()方法没有原生处理阿拉伯文的字形连写与RTL排版规则,导致每个字符被独立渲染,出现了不必要的分隔。

下面提供两种符合你要求(核心基于Pygame)的修复方案:

方案1:升级到Pygame Community Edition(推荐)

Pygame Community Edition(pygame-ce)是官方维护的分支,对非拉丁文字的排版支持做了大幅改进,原生支持阿拉伯文的连写和RTL方向,无需额外依赖库。

步骤:

  1. 安装pygame-ce:
pip install pygame-ce
  1. 修改代码(字体需支持阿拉伯文):
import pygame

pygame.display.init()
pygame.font.init()
win = pygame.display.set_mode((100, 100))
# 确保使用的字体支持阿拉伯文,可替换为你的字体路径
font = pygame.font.Font('./arial.ttf', 10)
# pygame-ce会自动处理阿拉伯文的连写与RTL方向
text = font.render('سلام', True, (255, 255, 255))

win.fill((0, 0, 0))
win.blit(text, (0, 0))
pygame.display.update()

for i in range(5):
    pygame.event.clear()
    pygame.time.delay(1000)
pygame.quit()

方案2:使用辅助库预处理文本(兼容原版Pygame)

如果需要继续使用原版Pygame,可以借助arabic-reshaper处理阿拉伯文的连写规则,python-bidi处理RTL排版方向,再交给Pygame渲染。

步骤:

  1. 安装依赖库:
pip install arabic-reshaper python-bidi
  1. 修改代码预处理文本:
import pygame
from arabic_reshaper import reshape
from bidi.algorithm import get_display

pygame.display.init()
pygame.font.init()
win = pygame.display.set_mode((100, 100))
font = pygame.font.Font('./arial.ttf', 10)

# 1. 重塑文本,处理阿拉伯文的连写字形
reshaped_text = reshape('سلام')
# 2. 调整文本方向,生成符合RTL规则的显示内容
display_text = get_display(reshaped_text)
# 3. 渲染预处理后的文本
text = font.render(display_text, True, (255, 255, 255))

win.fill((0, 0, 0))
win.blit(text, (0, 0))
pygame.display.update()

for i in range(5):
    pygame.event.clear()
    pygame.time.delay(1000)
pygame.quit()

额外提示:

  • 确保你使用的字体包含阿拉伯文的连写字形,否则即使预处理也可能显示异常。可以尝试系统自带的阿拉伯字体,比如Segoe UI Arabic,用pygame.font.SysFont("Segoe UI Arabic", 10)调用。

内容的提问来源于stack exchange,提问作者mhn2

火山引擎 最新活动