python画圆填色_如何用python在图像上绘制不同笔触和填充颜色的文本?

1586010002-jmsa.png

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.

2hpYT.png

I tried to do this with PIL but there was no option for setting the stroke color.

解决方案

Using cairo (with much code taken from here):

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")

4brSu.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值