Cairo module

Travis Griggs travisgriggs at gmail.com
Tue Feb 3 17:19:30 EST 2015


> On Feb 3, 2015, at 1:00 PM, Poul Riis <priisdk at gmail.com> wrote:
> 
> I just tried the Cairo Python module.
> I ran the test file below.
> It works perfectly but instead of saving the resulting image as a file I want to see it displayed directly on the screen.
> How can I do that?
> 

I have quiet a bit of experience with Cairo (I wrote language bindings for it in Smalltalk and had the time of my life with it there); I have no experience with the pycairo bindings.

> 
> import math
> import cairo
> 
> WIDTH, HEIGHT = 256, 256
> 
> surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, WIDTH, HEIGHT)

This is your basic problem right here. And ImageSurface is for creating an Image (sometimes called a raster graphic or bitmap). If you want to display directly to your screen, you need to create a surface that binds to your screen’s display functionality. There is one for each main operating system:

Win32Surface
XLibSurface
QuartzSurface (I see that this is missing from the pycairo documentation, but it is in the cairo documentation, and the pycairo.c file at least has some reference to it)

Allocating one of these involves getting handles (and other information) for a given window on screen of your host OS and creating the surface from it.


> ctx = cairo.Context (surface)
> 
> ctx.scale (WIDTH, HEIGHT) # Normalizing the canvas
> 
> pat = cairo.LinearGradient (0.0, 0.0, 0.0, 1.0)
> pat.add_color_stop_rgba (1, 0.7, 0, 0, 0.5) # First stop, 50% opacity
> pat.add_color_stop_rgba (0, 0.9, 0.7, 0.2, 1) # Last stop, 100% opacity
> 
> ctx.rectangle (0, 0, 1, 1) # Rectangle(x0, y0, x1, y1)
> ctx.set_source (pat)
> ctx.fill ()
> 
> ctx.translate (0.1, 0.1) # Changing the current transformation matrix
> 
> ctx.move_to (0, 0)
> ctx.arc (0.2, 0.1, 0.1, -math.pi/2, 0) # Arc(cx, cy, radius, start_angle, stop_angle)
> ctx.line_to (0.5, 0.1) # Line to (x,y)
> ctx.curve_to (0.5, 0.2, 0.5, 0.4, 0.2, 0.8) # Curve(x1, y1, x2, y2, x3, y3)
> ctx.close_path ()
> 
> ctx.set_source_rgb (0.3, 0.2, 0.5) # Solid color
> ctx.set_line_width (0.02)
> ctx.stroke ()
> 
> surface.write_to_png ("example.png") # Output to PNG 
> -- 
> https://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list