Save the contents of a Gtk.DrawingArea or Cairo pattern to an image on disk

后端 未结 2 1785
误落风尘
误落风尘 2020-12-21 22:27

I\'ve got a small PyGI project which uses a Cairo image surface, which I then scale with a surface pattern and render on a Gtk.DrawingArea.

I\'d like to write the

相关标签:
2条回答
  • 2020-12-21 23:12

    Ok, I found a way:

    Remembering that Gtk.DrawingArea derives from Gtk.Window, I could use the Gdk.pixbuf_get_from_window() function to get the contents of the drawing area into a GdkPixbuf.Pixbuf and then use the GdkPixbuf.Pixbuf.savev() function to write the pixbuf as an image on disk.

    def drawing_area_write(self):
        # drawingarea1 is a Gtk.DrawingArea
        window = self.ui.drawingarea1.get_window()
    
        # Some code to get the coordinates for the image, which is centered in the
        # in the drawing area. You can ignore it for the purpose of this example
        src_x, src_y = self.get_centered_coordinates(self.ui.drawingarea1,
                                                     self.surface)
        image_height = self.surface.get_height() * self.scale_factor
        image_width = self.surface.get_width() * self.scale_factor
    
        # Fetch what we rendered on the drawing area into a pixbuf
        pixbuf = Gdk.pixbuf_get_from_window(window, src_x, src_y,
                                          image_width, image_height)
    
        # Write the pixbuf as a PNG image to disk
        pixbuf.savev('/tmp/testimage.png', 'png', [], [])
    

    While this works, it'd still be nice to see if someone could confirm this is the right way or to see if there is any other alternative.

    0 讨论(0)
  • 2020-12-21 23:22

    I found another approach, using the Cairo context passed to the handler of draw events, but it resulted in capturing a region of the parent window that was larger than the DrawingArea.

    What worked for me was to use the PixBuf as you have shown, but first calling the queue_draw() method for the DrawingArea, to force a full rendering, and waiting for the event to be processed (easy enough, I already had a draw handler). Otherwise, the resulting images can be partially undrawn.

    0 讨论(0)
提交回复
热议问题