gpt4 book ai didi

python - 使用 Pango 和 Cairo (Pycairo) 使线条适合宽度

转载 作者:太空狗 更新时间:2023-10-30 01:29:41 28 4
gpt4 key购买 nike

我有几行文本,我希望每行的宽度(缩放字体大小)适合上下文的宽度。有没有办法做到这一点?我为此使用了 pangocairo 和 python。

最佳答案

我希望有时间找到可行的解决方案,但您可以从以下内容开始:

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)

结果:

result

我将改进这个算法作为练习留给读者,你可以尝试:

  • 在缩放字体和调整后验证布局的宽度
  • 以大字体显示并缩放pangocairo_context
  • 我不知道,事实上我对 pycairo 一无所知,直到我阅读了您的问题并查阅了文档。

关于python - 使用 Pango 和 Cairo (Pycairo) 使线条适合宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14750093/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com