From 87db9987c8ec762c567e6e11856026b77f9981fd Mon Sep 17 00:00:00 2001 From: Martin Lindhe Date: Thu, 21 Dec 2017 13:34:36 +0100 Subject: [PATCH] add an example using a custom mouse cursor example: cargo run --example cursor --features="image gfx" assets/cursor.png --- Cargo.toml | 4 +++ assets/cursor.png | Bin 0 -> 172 bytes examples/cursor.rs | 67 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+) create mode 100644 assets/cursor.png create mode 100644 examples/cursor.rs diff --git a/Cargo.toml b/Cargo.toml index ae54c457832..26c31d9e712 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,6 +66,10 @@ name = "audio-wav" [[example]] name = "audio-whitenoise" +[[example]] +required-features = ["image", "gfx"] +name = "cursor" + [[example]] name = "demo" diff --git a/assets/cursor.png b/assets/cursor.png new file mode 100644 index 0000000000000000000000000000000000000000..2118eb86ea319ded5001c60636e466e8654ccfcf GIT binary patch literal 172 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnF3?v&v(vJfvp#Yx{R|ZA~$Cx^XNp~2kcIu_{ znkKYKy!Olm$}*M&`2{mLJiCzw6N*-_+(P^iOH-TJW98bg=d#Wzp$P!VRycqF literal 0 HcmV?d00001 diff --git a/examples/cursor.rs b/examples/cursor.rs new file mode 100644 index 00000000000..60656038ea4 --- /dev/null +++ b/examples/cursor.rs @@ -0,0 +1,67 @@ +extern crate sdl2; + +use std::env; +use std::path::Path; +use sdl2::event::Event; +use sdl2::image::{LoadSurface, INIT_PNG, INIT_JPG}; +use sdl2::keyboard::Keycode; +use sdl2::mouse::Cursor; +use sdl2::pixels::Color; +use sdl2::gfx::primitives::DrawRenderer; +use sdl2::surface::Surface; + +pub fn run(png: &Path) { + + let sdl_context = sdl2::init().unwrap(); + let video_subsystem = sdl_context.video().unwrap(); + let _image_context = sdl2::image::init(INIT_PNG | INIT_JPG).unwrap(); + let window = video_subsystem.window("rust-sdl2 demo: Cursor", 800, 600) + .position_centered() + .build() + .unwrap(); + + let mut canvas = window.into_canvas().software().build().unwrap(); + + let surface = match Surface::from_file(png) { + Ok(surface) => surface, + Err(err) => panic!("failed to load cursor image: {}", err) + }; + let cursor = match Cursor::from_surface(surface, 0, 0) { + Ok(cursor) => cursor, + Err(err) => panic!("failed to load cursor: {}", err) + }; + cursor.set(); + + canvas.clear(); + canvas.present(); + + let mut events = sdl_context.event_pump().unwrap(); + + 'mainloop: loop { + for event in events.poll_iter() { + match event { + Event::Quit{..} | + Event::KeyDown {keycode: Option::Some(Keycode::Escape), ..} => + break 'mainloop, + Event::MouseButtonDown {x, y, ..} => { + let color = Color::RGB(255, 255, 255); + canvas.pixel(x as i16, y as i16, color).unwrap(); + canvas.present(); + } + _ => {} + } + } + } +} + + +fn main() { + + let args: Vec<_> = env::args().collect(); + + if args.len() < 2 { + println!("Usage: cargo run /path/to/image.(png|jpg)") + } else { + run(Path::new(&args[1])); + } +}