Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Created May 26, 2023 01:14
Show Gist options
  • Save matthewjberger/1ac8886702f1121b9c44d2b09a6708da to your computer and use it in GitHub Desktop.
Save matthewjberger/1ac8886702f1121b9c44d2b09a6708da to your computer and use it in GitHub Desktop.
Put a pixel on the screen with Rust!
[package]
name = "pixel"
version = "0.1.0"
edition = "2021"
[dependencies]
sdl2 = { version = "0.34.5", features = ["bundled"] }
use sdl2::{event::Event, keyboard::Keycode, pixels::Color};
const WIDTH: u32 = 800;
const HEIGHT: u32 = 600;
const PIXEL_SIZE: u32 = 1;
fn main() -> Result<(), String> {
let sdl_context = sdl2::init()?;
let video_subsystem = sdl_context.video()?;
let window = video_subsystem
.window("SDL2 Green Pixel", WIDTH, HEIGHT)
.position_centered()
.build()
.map_err(|e| e.to_string())?;
let mut canvas = window.into_canvas().build().map_err(|e| e.to_string())?;
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,
_ => {}
}
}
canvas.set_draw_color(Color::RGB(0, 0, 0));
canvas.clear();
canvas.set_draw_color(Color::RGB(0, 255, 0));
canvas.fill_rect(sdl2::rect::Rect::new(
(WIDTH / 2) as i32,
(HEIGHT / 2) as i32,
PIXEL_SIZE,
PIXEL_SIZE,
))?;
canvas.present();
::std::thread::sleep(::std::time::Duration::new(0, 1_000_000_000u32 / 60));
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment