[cairo] Keeping previously drawn shapes after 'draw' event?

Theo Veenker theo.veenker at beexy.nl
Fri Apr 3 18:53:19 UTC 2020

On 03/04/2020 18:54, desktopdave wrote:
> Hi,
> I am trying to port a tkinter paint app(ms paint clone) to
> pygobject/pygtk. Tkinter uses a sophisticated canvas widget, I am trying
> to figure out how to emulate it using Gtk.DrawingArea.
> I have worked out how to get a solid line(rectangle, oval etc) that
> shrinks/grows as I move the mouse - before button1 release, here's the
> basic code.
> def draw_brush(self, da, event):
>          """Draw something"""
>          ctx = cairo.Context(self.surface)
>          # Set white background
>          ctx.set_source_rgb(1, 1, 1)
>          ctx.paint()
>          # Draw selected shape chosen by user
>          self.execute_selected_method(ctx)
>          self.canvas.queue_draw()
> My problem is that by setting the background white on each draw, I get
> the solid growing/shrinking line(rectangle etc) effect needed, but it
> also means that any previously drawn shape is erased at next draw event.
> I need to somehow store the previous draws to the surface and reinstate
> them on each draw event, so the user can paint a picture.

I think you need to make a 'virtual' drawing, that is, a hierarchy of 
graphic objects. To change the drawing you adapt the attributes of your 
objects and then when done with all of them call a method that clears 
your surface and draws all the graphic objects. Perhaps you can use a 
cairo recording surface (I have never played with it). The benefit of 
such an approach is that you can change the drawing as many times as you 
want, you only need to actually draw it onto a surface once every frame 

If you have a very complex drawing (lots of graphic objects) it may be 
considerably more efficient if you find out which area of your drawing 
actually will change and use clipping.



Theo Veenker  |  Beexy - Behavioral Experiment Software
+31(0)524-541531  |  +31(0)6-42525777 mobile
theo.veenker at beexy.nl  |  www.beexy.nl

More information about the cairo mailing list