pycairoで文字列の領域を求めるには、以下のコードを実行します。以下の例では文字列の領域を暗い青で塗りつぶしています。
# coding=UTF-8
import cairo
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 200, 200)
ctx = cairo.Context(surface)
ctx.select_font_face("MS 明朝", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
x = 10
y = 100
ctx.set_font_size(40);
message = "日本語"
(x_bearing, y_bearing, width, height,
x_advance, y_advance) = (
ctx.text_extents(message))
ctx.set_source_rgb(0x11/float(0xff), 0x33/float(0xff), 0x77/float(0xff))
print "x_bearing:", x_bearing
print "y_bearing:", y_bearing
print "width:", width
print "height:", height
print "x_advance:", x_advance
print "y_advance:", y_advance
ctx.rectangle(x+x_bearing, y+y_bearing, width, height)
ctx.fill()
ctx.move_to(x,y)
ctx.set_source_rgb(0xbb/float(0xff), 0xdd/float(0xff), 0xff/float(0xff))
ctx.show_text(message)
surface.write_to_png('sample1019a.png')
出力画像(sample1019a.png)
動作環境
Python2.6.1, GTK+2.16.0, pycairo1.4.12-2
関連項目
pycairoのまとめpycairoをWindowsにインストール