gtkmm – example 17

This is part of a more general work dedicated to gtkmm accessible here. This example shows how to resize the drawing area according to the window size.

capture

Download


Source code


main.cpp

#include 
#include 


int main(int argc, char* argv[])
{
	// Initialize gtkmm and create the main window
	Glib::RefPtr app = Gtk::Application::create(argc, argv, "www.lucidarme.me");
	Gtk::Window window;
	// Set window size
	window.resize(600,400);

	// Create the drawing
	Drawing Dwg;

	// Insert the drawing in the window
	window.add(Dwg);

	// Show the drawing
	Dwg.show();

	// Start main loop
	return app->run(window);
}

drawing.h

#ifndef DRAWING_H
#define DRAWING_H

#include 
#include 

class Drawing : public Gtk::DrawingArea
{
public:
	Drawing();

protected:
	//Override default signal handler:
	virtual bool on_draw(const Cairo::RefPtr& cr);

private:
	Glib::RefPtr image;
};

#endif // DRAWING_H

drawing.cpp

#include "drawing.h"

Drawing::Drawing()
{
	// Load the image
	image = Gdk::Pixbuf::create_from_file("gtk.png");
}


bool Drawing::on_draw(const Cairo::RefPtr& cr)
{
	// Get drawing area size
	Gtk::Allocation allocation = get_allocation();
	const int width = allocation.get_width();
	const int height = allocation.get_height();

	// Scale the image to the area
	cr->scale((double)width/image->get_width(),(double)height/image->get_height());
	// Place the image at 0,0
	Gdk::Cairo::set_source_pixbuf(cr, image, 0,0);
	// Update the area where the image is located
	cr->rectangle(0, 0, image->get_width(), image->get_height());
	// Fill the area with the image
	cr->fill();

	return true;
}

Leave a Reply

Your email address will not be published. Required fields are marked *