如何用python在图像上绘制不同笔触和填充颜色的文本? [英] How can I draw text with different stroke and fill colors on images with python?
本文介绍了如何用python在图像上绘制不同笔触和填充颜色的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用python在图像上绘制具有不同笔触和填充颜色的文本?
How can I draw text with different stroke and fill colors on images with python?
这是一些红色笔触和灰色填充的文字。
Here is some text with red stroke and gray fill.
我尝试用PIL执行此操作,但没有设置笔触颜色的选项。
I tried to do this with PIL but there was no option for setting the stroke color.
推荐答案
import cairo
def text_extent(font, font_size, text, *args, **kwargs):
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 0, 0)
ctx = cairo.Context(surface)
ctx.select_font_face(font, *args, **kwargs)
ctx.set_font_size(font_size)
return ctx.text_extents(text)
text='Example'
font="Sans"
font_size=55.0
font_args=[cairo.FONT_SLANT_NORMAL]
(x_bearing, y_bearing, text_width, text_height,
x_advance, y_advance) = text_extent(font, font_size, text, *font_args)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(text_width), int(text_height))
ctx = cairo.Context(surface)
ctx.select_font_face(font, *font_args)
ctx.set_font_size(font_size)
ctx.move_to(-x_bearing, -y_bearing)
ctx.text_path(text)
ctx.set_source_rgb(0.47, 0.47, 0.47)
ctx.fill_preserve()
ctx.set_source_rgb(1, 0, 0)
ctx.set_line_width(1.5)
ctx.stroke()
surface.write_to_png("/tmp/out.png")
这篇关于如何用python在图像上绘制不同笔触和填充颜色的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文