2

I have a Gtk::DrawingArea which is inside a Gtk::ScrolledWindow. I'm trying to save the DrawingArea to a file, so I do the following in the DrawingArea signal_draw()'s handler :

Cairo::RefPtr<Cairo::Surface> surf = context -> get_target();
surf -> write_to_png("image");

But this only saves the part of the drawing area which is currently visible in the ScrolledWindow. How do I save the full image, including the part that is not currently visible?

Also, I can only do this in the handler of signal_draw, because there I can get the Cairo::Context. Is it posible to get this context anywhere else?

EDIT:

Thanks to andlabs's link I got it working:

#include <gtkmm.h>
#include <cairomm/context.h>
#include <cairomm/enums.h>
bool draw(const Cairo::RefPtr<Cairo::Context>& c){
    c->set_source_rgb(0,0,0);
    c->rectangle(400,50,50,50);
    c->fill();
    return true;
}
int main(int argc, char* argv[]){
    Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "my.test");
    Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create();
    builder -> add_from_file("gui.glade");
    Gtk::DrawingArea* drawing;
    Gtk::Window* win;
    builder -> get_widget("window", win);
    builder -> get_widget("drawing", drawing);
    drawing->signal_draw().connect(sigc::ptr_fun(&draw));
    Cairo::RefPtr<Cairo::Surface> surface;
    surface = Cairo::ImageSurface::create(Cairo::FORMAT_ARGB32,500,300);
    Cairo::RefPtr<Cairo::Context> c = Cairo::Context::create(surface);
    draw(c);
    surface->write_to_png("image");
    app->run(*win);

}

Now, can I set the DrawingArea's context to the context created in main(), so I don't have to call draw(c) manually to keep them synced?

Chrischpo
  • 145
  • 1
  • 11
  • 1
    No, but you can create your own Cairo context in memory, draw to that, and save that to a file. See [the `main()` function of the example here](https://developer.gnome.org/pango/unstable/pango-Cairo-Rendering.html#pango-Cairo-Rendering.description). You'll need to genericize your `draw` handler to both draw the entire area (for saving to a file) and just the part that needs redrawing (for drawing to the GtkDrawingArea). – andlabs Jun 10 '15 at 15:29
  • To signal that a widget needs to be redrawn, use `gtk_widget_queue_draw()` or whatever the gtkmm equivalent is. There are variants for drawing only a certain part of the widget as well. The Cairo context in the `draw` handler is created on each draw; I don't think there's a way to give a fixed context to the widget. – andlabs Jun 15 '15 at 00:06

0 Answers0