Chapter 9: Implementing 2D Animation and Graphics

Chapter 9: Implementing 2D Animation and Graphics with Cairo in Vala

9.1 Introduction

Cairo is a powerful 2D graphics library that integrates seamlessly with Vala and GTK 3.0+. This chapter will guide you through the basics of creating 2D animations and graphics using Cairo. You'll learn how to draw shapes, use colors, and animate these elements in a GTK application.


9.2 Getting to Know Cairo

Cairo is a vector-based graphics library, allowing you to draw in terms of points, lines, and curves, which are scalable and render cleanly at any size. It's used extensively in the GNOME desktop environment for rendering graphical user interface elements.


9.3 Setting Up Your Project

First, ensure you have the necessary packages:

sudo apt-get install libcairo2-dev libgtk-3-dev

Then, set up a basic Vala project with GTK and Cairo. Your project structure might look like this:


9.4 Drawing Basic Shapes with Cairo

Start by creating a simple window with a drawing area that allows a small red ball to move horizontally

across the screen:

ValaCourse.vala: The main application file.


public class MainWindow : Gtk.Window {

    public MainWindow() {

        this.title = "2D Graphics with Cairo";

        this.window_position = Gtk.WindowPosition.CENTER;

        this.destroy.connect(Gtk.main_quit);


        var drawingArea = new Gtk.DrawingArea();

        drawingArea.set_size_request(200, 100);

        drawingArea.draw.connect((widget, cr) => {

            return display(widget, cr);

        });

        this.add(drawingArea);

        this.show_all();

        GLib.Timeout.add(16, () => {

            return update_frame(drawingArea);

        }); // Update frame every 16 milliseconds

    }


    private double x_position = 0;


    private bool display(Gtk.Widget widget, Cairo.Context cr) {

        cr.set_source_rgb(0, 0, 0); // Black background

        cr.paint();

    

        // Draw a moving ball

        cr.set_source_rgb(1, 0, 0); // Red color

        cr.arc(x_position, 50, 10, 0, 2 * Math.PI); // Ball

        cr.fill();

    

        return false; // Return false to indicate no further drawing is required

    }


    private bool update_frame(Gtk.DrawingArea drawingArea) {

        x_position += 2;

        if (x_position > drawingArea.get_allocated_width()) {

            x_position = 0;

        }

    

        drawingArea.queue_draw(); // Redraw the window

        return true; // Continue the timeout

    }

}


void main(string[] args) {

    Gtk.init(ref args);

    new MainWindow();

    Gtk.main();

}


Compile String:

In Terminal type to compile:

valac -X -w -g ValaCourse.vala --pkg gtk+-3.0

Run the App

In Terminal type:

./ValaCourse


Shapes and Paths: Experiment with different shapes and paths. Use methods like move_to, line_to, curve_to, etc.

Colors and Gradients: Use different colors and gradients for more visually appealing graphics.

Text Rendering: Render text with various fonts and styles.

Image Loading: Load and display images using Cairo's image surface capabilities.

9.7 Best Practices

Performance: Be mindful of performance. Redrawing only the necessary parts of the window can improve efficiency.

Resource Management: Clean up any resources you create, like Cairo.Context, to prevent memory leaks.

9.8 Conclusion

This chapter has introduced you to the basics of 2D graphics and animation using Cairo in a Vala and GTK 3.0+ environment. By leveraging Cairo's capabilities, you can add engaging visual elements to your applications, enhancing the overall user experience.


This chapter serves as an introduction to 2D graphics and animations in Vala using Cairo, providing the foundational skills needed to create visually appealing and dynamic GTK applications. It emphasizes hands-on learning with practical examples, encouraging readers to explore Cairo's extensive graphics capabilities.