使用Pango和Cairo(Pycairo)使线条适合宽度 [英] Fit line to width with Pango and Cairo (Pycairo)

查看:473
本文介绍了使用Pango和Cairo(Pycairo)使线条适合宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've several lines of text and I'd like each to fit in width (scaling the font size) to the width of the Context. Is there a way of doing this? I'm using pangocairo and python for this.

推荐答案

我希望有时间来寻求可行的解决方案,但您可以从类似以下的内容开始:

I wish to have time for a working solution, but you can start with something like:

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)

结果:

我将继续改进该算法,作为读者的练习,您可以尝试:

I will left improving this algorithm as an exercise for the reader, you can try to:

  • 缩放字体并进行调整后,验证布局的宽度
  • 渲染大字体并缩放pangocairo_context
  • 我不知道,实际上我对pycairo一无所知,直到我读完您的问题并仔细阅读了文档.
  • verify the width of the layout after scaling the font and adjusting
  • render in a big font size and scale pangocairo_context instead
  • I don't know, in fact I knew nothing about pycairo until I read your question and goggled for the docs.

这篇关于使用Pango和Cairo(Pycairo)使线条适合宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆