[cairo] Optimizing code

Thomas Dybdahl Ahle lobais at gmail.com
Tue Sep 4 07:42:01 PDT 2007

Hi, I draw a background in an application, which is based partly on
get_style().dark[gtk.STATE_NORMAL], partly on (97, 97, 97) and partly on
a black/white/transparant png.

I merge them together with the code:

newcolor = self.get_style().dark[gtk.STATE_NORMAL]
newcolor = (color.blue/256, color.green/256, color.red/256)

# Get mostly transparant shadowy image
surface = cairo.ImageSurface.create_from_png(path)

# Clone surface on gray background
data = array ('B', 'a' * surface.get_width() * surface.get_height() * 4)
surf = cairo.ImageSurface.create_for_data (data, cairo.FORMAT_ARGB32,
        surface.get_width(), surface.get_height(), surface.get_stride())
ctx = cairo.Context (surf)
ctx.rectangle (0, 0, surface.get_width(), surface.get_height())
ctx.set_source_surface(surface, 0, 0)

# Add 'newcolor' to all (non aplha) pixels and divide by three
for pixel in xrange(0, len(data), 4):
    for color in xrange(3):
        data[pixel+color] = (newcolor[color] + data[pixel+color]) /3

# Make new surface from data
self.surface = cairo.ImageSurface.create_for_data (
    data, cairo.FORMAT_ARGB32,
    surface.get_width(), surface.get_height(), surface.get_stride())

But it works kinda slow.
I know it's python and it's supposed to be a little slow, but I was
wondering if there was something on the cairo front I could do smarter?

Med venlig hilsen,
Best regards,

More information about the cairo mailing list