iced_core/
svg.rs

1//! Load and draw vector graphics.
2use crate::{Color, Radians, Rectangle, Size};
3
4use rustc_hash::FxHasher;
5use std::borrow::Cow;
6use std::hash::{Hash, Hasher as _};
7use std::path::PathBuf;
8use std::sync::Arc;
9
10/// A raster image that can be drawn.
11#[derive(Debug, Clone, PartialEq)]
12pub struct Svg<H = Handle> {
13    /// The handle of the [`Svg`].
14    pub handle: H,
15
16    /// The [`Color`] filter to be applied to the [`Svg`].
17    ///
18    /// If some [`Color`] is set, the whole [`Svg`] will be
19    /// painted with it—ignoring any intrinsic colors.
20    ///
21    /// This can be useful for coloring icons programmatically
22    /// (e.g. with a theme).
23    pub color: Option<Color>,
24
25    /// The rotation to be applied to the image; on its center.
26    pub rotation: Radians,
27
28    /// The opacity of the [`Svg`].
29    ///
30    /// 0 means transparent. 1 means opaque.
31    pub opacity: f32,
32}
33
34impl Svg<Handle> {
35    /// Creates a new [`Svg`] with the given handle.
36    pub fn new(handle: impl Into<Handle>) -> Self {
37        Self {
38            handle: handle.into(),
39            color: None,
40            rotation: Radians(0.0),
41            opacity: 1.0,
42        }
43    }
44
45    /// Sets the [`Color`] filter of the [`Svg`].
46    pub fn color(mut self, color: impl Into<Color>) -> Self {
47        self.color = Some(color.into());
48        self
49    }
50
51    /// Sets the rotation of the [`Svg`].
52    pub fn rotation(mut self, rotation: impl Into<Radians>) -> Self {
53        self.rotation = rotation.into();
54        self
55    }
56
57    /// Sets the opacity of the [`Svg`].
58    pub fn opacity(mut self, opacity: impl Into<f32>) -> Self {
59        self.opacity = opacity.into();
60        self
61    }
62}
63
64impl From<&Handle> for Svg {
65    fn from(handle: &Handle) -> Self {
66        Svg::new(handle.clone())
67    }
68}
69
70/// A handle of Svg data.
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct Handle {
73    id: u64,
74    data: Arc<Data>,
75}
76
77impl Handle {
78    /// Creates an SVG [`Handle`] pointing to the vector image of the given
79    /// path.
80    pub fn from_path(path: impl Into<PathBuf>) -> Handle {
81        Self::from_data(Data::Path(path.into()))
82    }
83
84    /// Creates an SVG [`Handle`] from raw bytes containing either an SVG string
85    /// or gzip compressed data.
86    ///
87    /// This is useful if you already have your SVG data in-memory, maybe
88    /// because you downloaded or generated it procedurally.
89    pub fn from_memory(bytes: impl Into<Cow<'static, [u8]>>) -> Handle {
90        Self::from_data(Data::Bytes(bytes.into()))
91    }
92
93    fn from_data(data: Data) -> Handle {
94        let mut hasher = FxHasher::default();
95        data.hash(&mut hasher);
96
97        Handle {
98            id: hasher.finish(),
99            data: Arc::new(data),
100        }
101    }
102
103    /// Returns the unique identifier of the [`Handle`].
104    pub fn id(&self) -> u64 {
105        self.id
106    }
107
108    /// Returns a reference to the SVG [`Data`].
109    pub fn data(&self) -> &Data {
110        &self.data
111    }
112}
113
114impl<T> From<T> for Handle
115where
116    T: Into<PathBuf>,
117{
118    fn from(path: T) -> Handle {
119        Handle::from_path(path.into())
120    }
121}
122
123impl Hash for Handle {
124    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
125        self.id.hash(state);
126    }
127}
128
129/// The data of a vectorial image.
130#[derive(Clone, Hash, PartialEq, Eq)]
131pub enum Data {
132    /// File data
133    Path(PathBuf),
134
135    /// In-memory data
136    ///
137    /// Can contain an SVG string or a gzip compressed data.
138    Bytes(Cow<'static, [u8]>),
139}
140
141impl std::fmt::Debug for Data {
142    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143        match self {
144            Data::Path(path) => write!(f, "Path({path:?})"),
145            Data::Bytes(_) => write!(f, "Bytes(...)"),
146        }
147    }
148}
149
150/// A [`Renderer`] that can render vector graphics.
151///
152/// [renderer]: crate::renderer
153pub trait Renderer: crate::Renderer {
154    /// Returns the default dimensions of an SVG for the given [`Handle`].
155    fn measure_svg(&self, handle: &Handle) -> Size<u32>;
156
157    /// Draws an SVG with the given [`Handle`], an optional [`Color`] filter, and inside the provided `bounds`.
158    fn draw_svg(&mut self, svg: Svg, bounds: Rectangle);
159}