input_handling/
input-handling.rs

1//! # Example: Input Handling
2//!
3//! This example allows you to move a red circle to the location of a click on the simulator
4//! screen, or move the circle using the arrow keys. Although input handling is not a part of the
5//! embedded-graphics API, the simulator can be used to emulate input controls in order to
6//! represent more complex UI systems such as touch screens.
7
8extern crate embedded_graphics;
9extern crate embedded_graphics_simulator;
10
11use embedded_graphics::{
12    pixelcolor::Rgb888,
13    prelude::*,
14    primitives::{Circle, PrimitiveStyle},
15};
16use embedded_graphics_simulator::{
17    sdl2::Keycode, OutputSettings, SimulatorDisplay, SimulatorEvent, Window,
18};
19
20const BACKGROUND_COLOR: Rgb888 = Rgb888::BLACK;
21const FOREGROUND_COLOR: Rgb888 = Rgb888::RED;
22const KEYBOARD_DELTA: i32 = 20;
23
24fn move_circle(
25    display: &mut SimulatorDisplay<Rgb888>,
26    old_center: Point,
27    new_center: Point,
28) -> Result<(), core::convert::Infallible> {
29    // Clear old circle
30    Circle::with_center(old_center, 200)
31        .into_styled(PrimitiveStyle::with_fill(BACKGROUND_COLOR))
32        .draw(display)?;
33
34    // Draw circle at new location
35    Circle::with_center(new_center, 200)
36        .into_styled(PrimitiveStyle::with_fill(FOREGROUND_COLOR))
37        .draw(display)?;
38
39    Ok(())
40}
41
42fn main() -> Result<(), core::convert::Infallible> {
43    let mut display: SimulatorDisplay<Rgb888> = SimulatorDisplay::new(Size::new(800, 480));
44    let mut window = Window::new("Click to move circle", &OutputSettings::default());
45
46    let mut position = Point::new(200, 200);
47    Circle::with_center(position, 200)
48        .into_styled(PrimitiveStyle::with_fill(FOREGROUND_COLOR))
49        .draw(&mut display)?;
50
51    'running: loop {
52        window.update(&display);
53
54        for event in window.events() {
55            match event {
56                SimulatorEvent::Quit => break 'running,
57                SimulatorEvent::KeyDown { keycode, .. } => {
58                    let delta = match keycode {
59                        Keycode::Left => Point::new(-KEYBOARD_DELTA, 0),
60                        Keycode::Right => Point::new(KEYBOARD_DELTA, 0),
61                        Keycode::Up => Point::new(0, -KEYBOARD_DELTA),
62                        Keycode::Down => Point::new(0, KEYBOARD_DELTA),
63                        _ => Point::zero(),
64                    };
65                    let new_position = position + delta;
66                    move_circle(&mut display, position, new_position)?;
67                    position = new_position;
68                }
69                SimulatorEvent::MouseButtonUp { point, .. } => {
70                    move_circle(&mut display, position, point)?;
71                    position = point;
72                }
73                _ => {}
74            }
75        }
76    }
77
78    Ok(())
79}