vizia_core/views/
image.rs

1use vizia_style::Url;
2
3use crate::prelude::*;
4
5/// A view which presents an image.
6pub struct Image {}
7
8impl Image {
9    /// Creates a new [Image] view.
10    pub fn new<T: ToString>(cx: &mut Context, img: impl Res<T>) -> Handle<'_, Self> {
11        // TODO: Make this reactive
12
13        Self {}.build(cx, |_| {}).bind(img, |handle, img| {
14            let img = BackgroundImage::Url(Url { url: img.get(&handle).to_string().into() });
15            handle.background_image(img);
16        })
17    }
18}
19
20impl View for Image {
21    fn element(&self) -> Option<&'static str> {
22        Some("image")
23    }
24}
25
26/// A view which presents an SVG image.
27pub struct Svg {}
28
29impl Svg {
30    /// Creates a new [Svg] view.
31    pub fn new<T>(cx: &mut Context, data: impl Res<T>) -> Handle<Self>
32    where
33        T: AsRef<[u8]> + 'static,
34    {
35        Self {}.build(cx, |_| {}).bind(data, |mut handle, data| {
36            let svg_data = data.get(&handle);
37            let h = format!("{:x}", fxhash::hash64(svg_data.as_ref()));
38
39            handle.context().load_svg(
40                &h,
41                svg_data.as_ref(),
42                ImageRetentionPolicy::DropWhenNoObservers,
43            );
44            handle.background_image(format!("'{}'", h).as_str()).hoverable(false);
45        })
46    }
47}
48
49impl View for Svg {
50    fn element(&self) -> Option<&'static str> {
51        Some("svg")
52    }
53}