我想渲染一个 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 ()
EDIT2:在我同事的帮助下,我们设法得到了与上述类似的结果。使用 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 插件也很令人沮丧,但我仍然相信这是完成任务的最佳方式。