def cairo_text_bbox(text, font_params, scale=1.0):
surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 8, 8)
ctx = cairo.Context(surf)
# The scaling must match the final context.
# If not there can be a mismatch between the computed extents here
# and those generated for the final render.
ctx.scale(scale, scale)
font = cairo_font(font_params)
if use_pygobject:
layout = pangocairo.create_layout(ctx)
pctx = layout.get_context()
fo = cairo.FontOptions()
fo.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
pangocairo.context_set_font_options(pctx, fo)
layout.set_font_description(font)
layout.set_text(text, len(text))
re = layout.get_pixel_extents()[1]
extents = (re.x, re.y, re.x + re.width, re.y + re.height)
else: # pyGtk
pctx = pangocairo.CairoContext(ctx)
pctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
layout = pctx.create_layout()
layout.set_font_description(font)
layout.set_text(text)
#print('@@ EXTENTS:', layout.get_pixel_extents()[1])
extents = layout.get_pixel_extents()[1]
w = extents[2] - extents[0]
h = extents[3] - extents[1]
x0 = - w // 2.0
y0 = - h // 2.0
return [x0,y0, x0+w,y0+h]
评论列表
文章目录