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    /// The border radius for the svg
34    pub border_radius: [f32; 4],
35}
36
37impl Svg<Handle> {
38    /// Creates a new [`Svg`] with the given handle.
39    pub fn new(handle: impl Into<Handle>) -> Self {
40        Self {
41            handle: handle.into(),
42            color: None,
43            rotation: Radians(0.0),
44            opacity: 1.0,
45            border_radius: [0.0; 4],
46        }
47    }
48
49    /// Sets the [`Color`] filter of the [`Svg`].
50    pub fn color(mut self, color: impl Into<Color>) -> Self {
51        self.color = Some(color.into());
52        self
53    }
54
55    /// Sets the rotation of the [`Svg`].
56    pub fn rotation(mut self, rotation: impl Into<Radians>) -> Self {
57        self.rotation = rotation.into();
58        self
59    }
60
61    /// Sets the opacity of the [`Svg`].
62    pub fn opacity(mut self, opacity: impl Into<f32>) -> Self {
63        self.opacity = opacity.into();
64        self
65    }
66
67    /// Sets the border radius of the [`Svg`]
68    pub fn border_radius(mut self, border_radius: impl Into<[f32; 4]>) -> Self {
69        self.border_radius = border_radius.into();
70        self
71    }
72}
73
74impl From<&Handle> for Svg {
75    fn from(handle: &Handle) -> Self {
76        Svg::new(handle.clone())
77    }
78}
79
80/// A handle of Svg data.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct Handle {
83    id: u64,
84    data: Arc<Data>,
85}
86
87impl Handle {
88    /// Creates an SVG [`Handle`] pointing to the vector image of the given
89    /// path.
90    pub fn from_path(path: impl Into<PathBuf>) -> Handle {
91        Self::from_data(Data::Path(path.into()))
92    }
93
94    /// Creates an SVG [`Handle`] from raw bytes containing either an SVG string
95    /// or gzip compressed data.
96    ///
97    /// This is useful if you already have your SVG data in-memory, maybe
98    /// because you downloaded or generated it procedurally.
99    pub fn from_memory(bytes: impl Into<Cow<'static, [u8]>>) -> Handle {
100        Self::from_data(Data::Bytes(bytes.into()))
101    }
102
103    fn from_data(data: Data) -> Handle {
104        let mut hasher = FxHasher::default();
105        data.hash(&mut hasher);
106
107        Handle {
108            id: hasher.finish(),
109            data: Arc::new(data),
110        }
111    }
112
113    /// Returns the unique identifier of the [`Handle`].
114    pub fn id(&self) -> u64 {
115        self.id
116    }
117
118    /// Returns a reference to the SVG [`Data`].
119    pub fn data(&self) -> &Data {
120        &self.data
121    }
122}
123
124impl<T> From<T> for Handle
125where
126    T: Into<PathBuf>,
127{
128    fn from(path: T) -> Handle {
129        Handle::from_path(path.into())
130    }
131}
132
133impl Hash for Handle {
134    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
135        self.id.hash(state);
136    }
137}
138
139/// The data of a vectorial image.
140#[derive(Clone, Hash, PartialEq, Eq)]
141pub enum Data {
142    /// File data
143    Path(PathBuf),
144
145    /// In-memory data
146    ///
147    /// Can contain an SVG string or a gzip compressed data.
148    Bytes(Cow<'static, [u8]>),
149}
150
151impl std::fmt::Debug for Data {
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        match self {
154            Data::Path(path) => write!(f, "Path({path:?})"),
155            Data::Bytes(_) => write!(f, "Bytes(...)"),
156        }
157    }
158}
159
160/// A [`Renderer`] that can render vector graphics.
161///
162/// [renderer]: crate::renderer
163pub trait Renderer: crate::Renderer {
164    /// Returns the default dimensions of an SVG for the given [`Handle`].
165    fn measure_svg(&self, handle: &Handle) -> Size<u32>;
166
167    /// Draws an SVG with the given [`Handle`], an optional [`Color`] filter, and inside the provided `bounds`.
168    fn draw_svg(&mut self, svg: Svg, bounds: Rectangle);
169}