[cairo] trouble with show_text in PyCairo.

Steve stevech1097 at yahoo.com.au
Fri Nov 7 17:30:25 PST 2008


On Fri, 2008-11-07 at 12:00 -0800, cairo-request at cairographics.org
wrote:
> I am new to cairo.
> 
> Here is my script
> 
> import cairo
> 
> WIDTH, HEIGHT = 400, 400
> 
> # Setup Cairo
> surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
> ctx = cairo.Context(surface)
> 
> # Set thickness of brush
> ctx.set_line_width(15)
> 
> # Draw out the triangle using absolute coordinates
> ctx.move_to(200, 100)
> ctx.line_to(300, 300)
> ctx.rel_line_to(-200, 0)
> 
> ctx.set_source_rgb(0.0, 0.0, 0.0)
> ctx.select_font_face("Georgia", cairo.FONT_SLANT_NORMAL,
> cairo.FONT_WEIGHT_BOLD)
> ctx.set_font_size(1.2)
> x_bearing, y_bearing, width, height = ctx.text_extents("a")[:4]
> ctx.move_to(0.5 - width / 2 - x_bearing, 0.5 - height / 2 - y_bearing)
> ctx.show_text("a")
> 
> ctx.close_path()
> # Apply the ink
> ctx.stroke()
> 
> # Output a PNG file
> surface.write_to_png("triangle.png")
> 
> 
> 
> 
> It causes an error:
> Traceback (most recent call last):
>   File "draw_image.py", line 20, in <module>
>     x_bearing, y_bearing, width, height = ctx.text_extents("a")[:4]
> MemoryError
> 
> Please tell me what is wrong with that script and how to fix that
> error?

You are probably exposing a bug in an old version of cairo. Try
upgrading to cairo 1.6.4 and pycairo 1.6.4. The code runs without error
for me (but does not draw anything useful looking).

The 'triangle code' does not draw a triangle - you need to draw the last
side:
ctx.move_to(200, 100)
ctx.line_to(300, 300)
ctx.rel_line_to(-200, 0)
ctx.close_path()

The text code tries to draw a tiny (1.2 pixel) 'a' partly outside the
top left of the picture.
Lines and paths are drawn with the (0,0) origin at the top left corner.
But text is drawn relative to the lower left corner of the text string.

Regards,
Steve



More information about the cairo mailing list