draw a window in rust

Drawing a window in Rust involves using a GUI library to create a window and a graphics library to draw on it. One commonly used GUI library in Rust is gtk-rs, while one commonly used graphics library is cairo.

Here's an example code snippet that creates a window using gtk-rs and draws a rectangle on it using cairo:

main.rs
extern crate gtk;
extern crate cairo;

use gtk::prelude::*;
use gtk::{Window, WindowType};
use cairo::Context;

fn main() {
    if let Err(err) = gtk::init() {
        println!("Failed to initialize GTK: {}", err);
        return;
    }

    let window = Window::new(WindowType::Toplevel);
    window.set_title("My Rust Window");
    window.set_default_size(400, 400);
    window.connect_delete_event(|_, _| {
        gtk::main_quit();
        Inhibit(false)
    });

    window.connect_draw(|win, ctx| {
        let width = win.get_allocated_width() as f64;
        let height = win.get_allocated_height() as f64;

        let rect_width = width * 0.75;
        let rect_height = height * 0.75;
        let rect_x = (width - rect_width) / 2.0;
        let rect_y = (height - rect_height) / 2.0;

        ctx.rectangle(rect_x, rect_y, rect_width, rect_height);
        ctx.set_source_rgba(1.0, 0.0, 0.0, 1.0); // red color
        ctx.fill();

        Inhibit(false)
    });

    window.show_all();

    gtk::main();
}
1019 chars
42 lines

This code snippet creates a window using gtk-rs, sets its title and size, and connects a function to handle the delete_event signal (which is emitted when the user clicks the "close" button on the window). In the draw signal handler, a rectangle is drawn on the window using cairo. Finally, the window is shown and the GTK+ main loop started.

gistlibby LogSnag