polyhorn_ui/assets/
image_source.rs

1//! Types to abstract away the source of an image that is drawn to the screen.
2
3use bytes::Bytes;
4
5use super::ImageAsset;
6use crate::geometry::Size;
7
8/// An image source describes the source of an image that can be passed to e.g.
9/// the Image component. An image source can either be a placeholder, an Asset
10/// or a Bytes (3rd party crate) object.
11#[derive(Clone, PartialEq)]
12pub enum ImageSource {
13    /// If you're loading a remote image, you might want to show a placeholder
14    /// instead. The placeholder is entirely transparent (unless you give the
15    /// containing component an opaque background color) but does have a size.
16    /// This size is subsequently used in calculating the layout.
17    ///
18    /// The benefit of this is that when the image is eventually completely
19    /// loaded and the component re-renders to show that image, the rest of the
20    /// layout will not change because it already anticipated the correct size
21    /// of the image.
22    Placeholder(Size<f32>),
23
24    /// This image source is backed by a local asset that is included in a
25    /// Polyhorn package.
26    Asset(ImageAsset),
27
28    /// This image source is backed by an PNG-encoded buffer.
29    Bytes(Bytes),
30}
31
32impl ImageSource {
33    /// Returns a placeholder image source with the given width and height.
34    pub fn placeholder(width: f32, height: f32) -> ImageSource {
35        ImageSource::Placeholder(Size::new(width, height))
36    }
37}
38
39impl Default for ImageSource {
40    fn default() -> Self {
41        ImageSource::Placeholder(Size::default())
42    }
43}
44
45impl From<ImageAsset> for ImageSource {
46    fn from(asset: ImageAsset) -> Self {
47        ImageSource::Asset(asset)
48    }
49}
50
51impl From<Bytes> for ImageSource {
52    fn from(bytes: Bytes) -> Self {
53        ImageSource::Bytes(bytes)
54    }
55}
56
57impl From<&'static [u8]> for ImageSource {
58    fn from(bytes: &'static [u8]) -> Self {
59        ImageSource::Bytes(Bytes::from_static(bytes))
60    }
61}