pixel_widgets/widget/
image.rs

1pub use crate::draw::ImageData;
2use crate::draw::Primitive;
3use crate::layout::{Rectangle, Size};
4use crate::node::{GenericNode, IntoNode, Node};
5use crate::style::Stylesheet;
6use crate::widget::Widget;
7use std::marker::PhantomData;
8
9/// A widget that display an image.
10pub struct Image<'a>(*const ImageData, PhantomData<&'a ()>);
11
12impl<'a> Image<'a> {
13    /// Sets the image to be displayed.
14    pub fn image(mut self, image: &'a ImageData) -> Self {
15        self.0 = image as _;
16        self
17    }
18
19    fn content(&self) -> &ImageData {
20        unsafe { self.0.as_ref().expect("image of `Image` must be set") }
21    }
22}
23
24impl<'a> Default for Image<'a> {
25    fn default() -> Self {
26        Self(std::ptr::null(), PhantomData)
27    }
28}
29
30unsafe impl<'a> Send for Image<'a> {}
31
32impl<'a, T: 'a> Widget<'a, T> for Image<'a> {
33    type State = ();
34
35    fn mount(&self) {}
36
37    fn widget(&self) -> &'static str {
38        "image"
39    }
40
41    fn len(&self) -> usize {
42        0
43    }
44
45    fn visit_children(&mut self, _: &mut dyn FnMut(&mut dyn GenericNode<'a, T>)) {}
46
47    fn size(&self, _: &(), style: &Stylesheet) -> (Size, Size) {
48        let width = match style.width {
49            Size::Shrink => Size::Exact(self.content().size.width()),
50            other => other,
51        };
52        let height = match style.height {
53            Size::Shrink => Size::Exact(self.content().size.height()),
54            other => other,
55        };
56        (width, height)
57    }
58
59    fn draw(&mut self, _: &mut (), layout: Rectangle, _: Rectangle, style: &Stylesheet) -> Vec<Primitive<'a>> {
60        vec![Primitive::DrawImage(self.content().clone(), layout, style.color)]
61    }
62}
63
64impl<'a, T: 'a> IntoNode<'a, T> for Image<'a> {
65    fn into_node(self) -> Node<'a, T> {
66        Node::from_widget(self)
67    }
68}