我有几行文本,我希望每行都适合 Context 的宽度(缩放字体大小)。有没有办法做到这一点?我为此使用 pangocairo 和 python。
问问题
1254 次
1 回答
2
我希望有时间找到一个可行的解决方案,但您可以从以下内容开始:
import cairo
import pango
import pangocairo
import sys
W = 500
H = int(1.4 * W)
surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, W, H)
context = cairo.Context(surf)
#draw a background rectangle:
context.rectangle(0, 0, W, H)
context.set_source_rgb(1, 1, 1)
context.fill()
#get font families:
font_map = pangocairo.cairo_font_map_get_default()
families = font_map.list_families()
# to see family names:
#print sorted([f.get_name() for f in font_map.list_families()])
# context.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
# Translates context so that desired text upperleft corner is at 0,0
text = """Fit line
to width with
Pango
and Cairo"""
fontname = "Arial"
context.set_source_rgb(0, 0, 0)
y = 0
for line in text.split("\n"):
pangocairo_context = pangocairo.CairoContext(context)
pangocairo_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
layout = pangocairo_context.create_layout()
font = pango.FontDescription(fontname + " 25")
layout.set_font_description(font)
layout.set_text(line)
pangocairo_context.update_layout(layout)
w, h = layout.get_pixel_size()
print w, h, y
context.translate(0, y)
pangocairo_context = pangocairo.CairoContext(context)
pangocairo_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
layout = pangocairo_context.create_layout()
font_descr = "{} {:0.1f}".format(fontname, float(W) / w * 25)
font = pango.FontDescription(font_descr)
layout.set_font_description(font)
layout.set_text(line)
_, y = layout.get_pixel_size()
pangocairo_context.update_layout(layout)
pangocairo_context.show_layout(layout)
with open("cairo_text.png", "wb") as image_file:
surf.write_to_png(image_file)
结果:
我将把改进这个算法作为练习留给读者,你可以尝试:
- 缩放字体并调整后验证布局的宽度
- 以大字体大小和比例
pangocairo_context
渲染 pycairo
我不知道,事实上,在我阅读您的问题并查看文档之前,我一无所知。
于 2015-03-03T01:50:23.817 回答