def cairo_text_bbox(text, font_params, spacing=0, 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:
status, attrs, plain_text, _ = pango.parse_markup(text, len(text), '\0')
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_spacing(spacing * pango.SCALE)
layout.set_text(plain_text, len(plain_text))
layout.set_attributes(attrs)
li = layout.get_iter() # Get first line of text
baseline = li.get_baseline() / pango.SCALE
re = layout.get_pixel_extents()[1] # Get logical extents
extents = (re.x, re.y, re.x + re.width, re.y + re.height)
else: # pyGtk
attrs, plain_text, _ = pango.parse_markup(text)
pctx = pangocairo.CairoContext(ctx)
pctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
layout = pctx.create_layout()
layout.set_font_description(font)
layout.set_spacing(spacing * pango.SCALE)
layout.set_text(plain_text)
layout.set_attributes(attrs)
li = layout.get_iter() # Get first line of text
baseline = li.get_baseline() / pango.SCALE
#print('@@ EXTENTS:', layout.get_pixel_extents()[1], spacing)
extents = layout.get_pixel_extents()[1] # Get logical extents
return [extents[0], extents[1], extents[2], extents[3], baseline]
评论列表
文章目录