Programmieren in Rust

Computergrafik: Multimedia-Schnittstelle

Inhaltsverzeichnis

  1. Einstieg

Einstieg

use sdl2::{pixels::Color, rect::Rect};
use sdl2::{event::Event, keyboard::Keycode};
use std::{time::Duration, thread::sleep};

type Error = Box<dyn std::error::Error>;

pub fn main() -> Result<(), Error> {
    let sdl_context = sdl2::init()?;
    let video_subsystem = sdl_context.video()?;
    let window = video_subsystem.window("Fenster", 960, 600)
        .position_centered().build()?;
    let mut canvas = window.into_canvas().build()?;

    canvas.set_draw_color(Color::RGB(0, 0, 0));
    canvas.clear();
    canvas.set_draw_color(Color::RGB(255, 255, 255));
    canvas.fill_rect(Rect::new(20, 20, 10, 10))?;
 
    canvas.present();

    let duration = Duration::from_millis(100); 
    let mut event_pump = sdl_context.event_pump()?;
    'running: loop {
        for event in event_pump.poll_iter() {
            match event {
                Event::Quit{..} |
                Event::KeyDown{keycode: Some(Keycode::Escape), ..} => {
                    break 'running
                },
                _ => {}
            }
        }
        sleep(duration);
    }
    Ok(())
}