def cairo_render_string(s,fontname=None,fontfile=None,size=None,bg=(0.0,0.0,0.0),fg=(0.9,0.9,0.9),pad=5):
"""Render a string using Cairo and the Cairo text rendering interface. Fonts can either be given
as a fontfile or as a fontname. Size should be in pixels (?). You can specify a background and
foreground color as RGB floating point triples. Images are padded by pad pixels on all sides."""
face = None
if fontfile is not None:
# "/usr/share/fonts/truetype/msttcorefonts/comic.ttf"
if fontfile in facecache:
face = facecache[fontfile]
else:
face = create_cairo_font_face_for_file(fontfile,0)
facecache[fontfile] = face
# make a guess at the size
w = max(100,int(size*len(s)))
h = max(100,int(size*1.5))
# possibly run through twice to make sure we get the right size buffer
for round in range(2):
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,w,h)
cr = cairo.Context(surface)
if face is not None:
cr.set_font_face(face)
else:
if fontname is None: fontname = "Helvetica"
cr.select_font_face(fontname)
if size is not None:
cr.set_font_size(size)
xbear,ybear,tw,th = cr.text_extents(s)[:4]
tw += 2*pad
th += 2*pad
if tw<=w and th<=h: break
w = tw
h = th
cr.set_source_rgb(*bg)
cr.rectangle(0,0,w,h)
cr.fill()
cr.move_to(-xbear+pad,-ybear+pad)
cr.set_source_rgb(*fg)
cr.show_text(s)
data = surface.get_data()
data = bytearray(data)
a = array(data,'B')
a.shape = (h,w,4)
a = a[:th,:tw,:3]
a = a[:,:,::-1]
return a
评论列表
文章目录