def pango_render_string(s,spec=None,fontfile=None,size=None,bg=(0.0,0.0,0.0),fg=(0.9,0.9,0.9),pad=5,
markup=1,scale=2.0,aspect=1.0,rotation=0.0):
"""Render a string using Cairo and the Pango 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. (Currently unimplemented.)"""
S = pango.SCALE
face = None
if fontfile is not None: raise Exception("can't load ttf file into Pango yet; use fontname")
# make a guess at the size
w = max(100,int(scale*size*len(s)))
h = max(100,int(scale*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 spec is not None: fd = pango.FontDescription(spec)
else: fd = pango.FontDescription()
if size is not None: fd.set_size(int(scale*size*S))
pcr = pangocairo.CairoContext(cr)
layout = pcr.create_layout()
layout.set_font_description(fd)
if not markup:
layout.set_text(s)
else:
layout.set_markup(s)
((xbear,ybear,tw,th),_) = layout.get_pixel_extents()
# print(xbear, ybear, tw, th)
tw = tw+2*pad
th = 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)
pcr.show_layout(layout)
data = surface.get_data()
data = bytearray(data)
a = array(data,'B')
a.shape = (h,w,4)
a = a[:th,:tw,:3]
a = a[:,:,::-1]
if rotation!=0.0: a = rotate(a,rotation,order=1)
a = zoom(a,(aspect/scale,1.0/scale/aspect,1.0),order=1)
return a
评论列表
文章目录