Skip to main content

matrix_gui/widgets/
staticimage.rs

1//! Static image widget for displaying images.
2//!
3//! This module provides a widget that displays a static image within
4//! a specified region. The image can be shown or hidden dynamically.
5
6use crate::prelude::*;
7use embedded_graphics::image::Image;
8
9/// Static image widget for displaying images.
10///
11/// This widget displays a static image within a specified region.
12/// The image can be shown or hidden dynamically using the
13/// `visible()` method.
14///
15/// # Type Parameters
16///
17/// * `'a` - The lifetime of the image data reference
18/// * `ID` - The widget ID type implementing [`WidgetId`]
19/// * `T` - The image type implementing [`ImageDrawable`]
20pub struct StaticImage<'a, ID, T> {
21    /// The region defining the image's position and size.
22    region: &'a Region<ID>,
23    /// Reference to the raw image data.
24    raw_img: &'a T,
25    /// Flag indicating whether the image should be shown.
26    show: bool,
27}
28
29impl<'a, ID: WidgetId, T: ImageDrawable> StaticImage<'a, ID, T> {
30    pub const fn new(region: &'a Region<ID>, raw_img: &'a T) -> Self {
31        Self {
32            region,
33            raw_img,
34            show: true,
35        }
36    }
37
38    pub const fn visible(mut self, show: bool) -> Self {
39        self.show = show;
40        self
41    }
42}
43
44impl<'a, DRAW, ID: WidgetId, T, COL> Widget<DRAW, COL> for StaticImage<'a, ID, T>
45where
46    COL: PixelColor,
47    DRAW: DrawTarget<Color = COL>,
48    T: ImageDrawable<Color = COL>,
49{
50    fn draw(&mut self, ui: &mut Ui<DRAW, COL>) -> GuiResult<Response> {
51        let widget_state = ui.get_widget_state(self.region.id())?;
52
53        if !widget_state.compare_set(RenderStatus::Rendered) {
54            let area = self.region.rectangle();
55            ui.clear_area(&area)?;
56
57            if self.show {
58                let image = Image::new(self.raw_img, area.top_left);
59                ui.draw(&image)?;
60            }
61        }
62        Ok(Response::Idle)
63    }
64}