gtkmm – exemple 20

Cet article fait parti d’un ensemble d’exemples et d’articles sur gtkmm consultables ici. Ce programme montre comment traiter les données issues de la molette de souris dans une zone de dessin (par exemple pour zommer).

capture

Téléchargement


Code source


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;

	// Create the drawing
	Drawing Dwg;


	// Insert the drawing in the window
	window.add(Dwg);
	// Resize the window
	window.resize(400,400);
	// Set the window title
	window.set_title("Mouse scroll");
	// 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);

    // Override mouse scroll event
    bool on_scroll_event(GdkEventScroll *ev);



private:
    // Image displayed
    Glib::RefPtr   image;
    // Scale of the image
    double                      scale;


};

#endif // DRAWING_H

drawing.cpp

#include "drawing.h"

Drawing::Drawing()
{
    // Load the image
    image = Gdk::Pixbuf::create_from_file("gtk.png");
    add_events(Gdk::BUTTON_PRESS_MASK | Gdk::SCROLL_MASK  |Gdk::SMOOTH_SCROLL_MASK);
    scale=1;
}


bool Drawing::on_scroll_event(GdkEventScroll *ev)
{
    // Update scale according to mouse scroll
    scale-=ev->delta_y/10.;
	if (scale<0.1) scale=0.1;
    std::cout << scale << std::endl;
    std::cout.flush();
    // Update drawing
    queue_draw();
    // There is probably a good reason to do this
    return true;
}




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(scale,scale);

    // Place the image at the center of the window
    Gdk::Cairo::set_source_pixbuf(cr, image, (width/2)/scale-image->get_width()/2,(height/2)/scale-image->get_height()/2);

    // Update the whole drawing area
    cr->rectangle(0, 0, get_allocation().get_width()/scale, get_allocation().get_width()/scale);
    // Fill the area with the image
    cr->fill();

    return true;
}

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *