maycoon_widgets/
image.rs

1use maycoon_core::app::context::AppContext;
2use maycoon_core::app::info::AppInfo;
3use maycoon_core::app::update::Update;
4use maycoon_core::layout::{LayoutNode, LayoutStyle, StyleNode};
5use maycoon_core::signal::MaybeSignal;
6use maycoon_core::vgi::{ImageBrush, ImageData, Scene};
7use maycoon_core::widget::{Widget, WidgetLayoutExt};
8use maycoon_theme::id::WidgetId;
9use maycoon_theme::theme::Theme;
10use nalgebra::Vector2;
11
12/// An image widget. Pretty self-explanatory.
13///
14/// See the [image](https://github.com/maycoon-ui/maycoon/blob/master/examples/image/src/main.rs) example for how to use it in practice.
15///
16/// ### Theming
17/// The widget itself only draws the underlying image, so theming is useless.
18pub struct Image {
19    image: MaybeSignal<ImageData>,
20    style: MaybeSignal<LayoutStyle>,
21}
22
23impl Image {
24    /// Create an image widget from the given [ImageData].
25    pub fn new(image: impl Into<MaybeSignal<ImageData>>) -> Self {
26        Self {
27            image: image.into(),
28            style: LayoutStyle::default().into(),
29        }
30    }
31
32    /// Set the image.
33    pub fn with_image(mut self, image: impl Into<MaybeSignal<ImageData>>) -> Self {
34        self.image = image.into();
35        self
36    }
37}
38
39impl WidgetLayoutExt for Image {
40    fn set_layout_style(&mut self, layout_style: impl Into<MaybeSignal<LayoutStyle>>) {
41        self.style = layout_style.into();
42    }
43}
44
45impl Widget for Image {
46    fn render(
47        &mut self,
48        scene: &mut dyn Scene,
49        _: &mut dyn Theme,
50        layout_node: &LayoutNode,
51        _: &AppInfo,
52        _: AppContext,
53    ) {
54        let image = self.image.get();
55        let brush = ImageBrush::new(image.clone());
56
57        scene.draw_image(
58            &brush,
59            None,
60            Vector2::new(layout_node.layout.location.x, layout_node.layout.location.y),
61        );
62    }
63
64    fn layout_style(&self) -> StyleNode {
65        StyleNode {
66            style: self.style.get().clone(),
67            children: Vec::new(),
68        }
69    }
70
71    fn update(&mut self, _: &LayoutNode, _: AppContext, _: &AppInfo) -> Update {
72        Update::empty()
73    }
74
75    fn widget_id(&self) -> WidgetId {
76        WidgetId::new("maycoon-widgets", "Image")
77    }
78}