Skip to main content
 首页 » 编程设计

python之在 python 中渲染矢量字母

2025年05月04日10bjzhanghao

我想渲染一个 truetype 字母以与 python 中的 shapely 模块一起使用。 (假设我想对字母进行一些形态学操作。)

到目前为止,我设法使用 cairo 将一封信写入 SVG 文件(见下文)。该字母在文件标题中保存为曲线。曲线基本上是我所需要的,但我相信一定有比保存、处理和加载 SVG 文件更优雅的方式来获取曲线。

第二个任务是以适用于匀称的格式加载曲线,但我认为这是可以完成的。

#!/usr/bin/env python 
#-*- coding: utf-8 -*- 
import cairo 
fo = file('test.svg', 'w') 
WIDTH, HEIGHT  = 256, 256 
surface = cairo.SVGSurface (fo, WIDTH, HEIGHT) ## Prepare a destination surface -> out to an SVG file! 
ctx = cairo.Context (surface) 
ctx.scale (WIDTH/1.0, HEIGHT/1.0) # Normalizing the canvas 
 
ctx.move_to (0.1, 0.9) 
ctx.set_font_size(1.) 
character = "a" 
ctx.show_text(character) 
 
surface.finish() 

提前感谢您的提示!


编辑:我发现可以使用 text_path() 而不是 show_text() 绘制一条真正的曲线,但我仍然无法读取这些点...

print ctx.text_path("b") 
ctx.set_source_rgb (0.3, 0.2, 0.5) # Solid color 
ctx.set_line_width (0.02) 
ctx.stroke () 


编辑2: 在我同事的帮助下,我们设法得到了与上述类似的结果。使用 fontforge 也可以渲染字形并将其保存为 SVG(在贝塞尔曲线中)。它可能对某人有用。

#!/usr/bin/python 
# -*- coding: utf-8 -*- 
## Outputs a glyph as a SVG, using FontForge (requires package 'python-fontforge') 
import fontforge 
f = fontforge.open("/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-R.ttf") 
g = f["Aring"] 
print g 
g.export("orig.svg") 

可选地,可以在保存 SVG 之前对字形执行形态学膨胀。 (但是,这是许多步骤中唯一需要的步骤。)

g.stroke("circular", 100, "round", "round", "removeinternal")  ## morphologic dilation of the glyph 
g.export("stroke.svg") 

还可以建立精确的边界框。

print "Stroked: g.boundingBox() =", g.boundingBox() 

顺便说一句,尝试编写即使是琐碎的 Inkscape 插件也很令人沮丧,但我仍然相信这是完成任务的最佳方法。

请您参考如下方法:

您可能需要使用 FreeType直接地。 glyph-vector.py example展示了如何获取字形矢量信息。