render_chars.py 文件源码

python
阅读 18 收藏 0 点赞 0 评论 0

项目:sha2017-lenny-face-generator 作者: polyfloyd 项目源码 文件源码
def render_string_to_image(string, height):
    surf = cairo.ImageSurface(cairo.FORMAT_RGB24, height * 4 * len(string), height)
    context = cairo.Context(surf)

    # Do some font metrics wizardry
    pangocairo_context = pangocairo.CairoContext(context)
    layout = pangocairo_context.create_layout()
    font = pango.FontDescription("Sans")
    font.set_absolute_size(height * pango.SCALE)
    layout.set_font_description(font)
    layout.set_text(string)
    exts = layout.get_pixel_extents()
    width = exts[1][2] + -exts[0][0]

    # Draw a background rectangle:
    context.rectangle(0, 0, width, height)
    context.set_source_rgb(1, 1, 1)
    context.fill()

    # Draw the text
    context.translate(-exts[0][0], -exts[0][1])
    context.set_source_rgb(0, 0, 0)
    pangocairo_context.update_layout(layout)
    pangocairo_context.show_layout(layout)

    # Crop the rendered image
    cropped = cairo.ImageSurface(cairo.FORMAT_RGB24, width, height)
    cropped_context = cairo.Context(cropped)
    cropped_context.rectangle(0, 0, width, height)
    cropped_context.set_source_surface(surf, 0, 0);
    cropped_context.fill()

    return cropped
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号