feat: SVG styling with icon fill color

This commit is contained in:
Michael Aaron Murphy 2022-11-16 17:42:41 +01:00 committed by Héctor Ramón Jiménez
parent 0249640213
commit 75ae0de9bd
No known key found for this signature in database
GPG key ID: 140CC052C94F138E
7 changed files with 137 additions and 22 deletions

View file

@ -7,6 +7,8 @@ use iced_native::Size;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::fs; use std::fs;
type Fill = Option<[u8; 4]>;
/// Entry in cache corresponding to an svg handle /// Entry in cache corresponding to an svg handle
pub enum Svg { pub enum Svg {
/// Parsed svg /// Parsed svg
@ -33,9 +35,9 @@ impl Svg {
#[derive(Debug)] #[derive(Debug)]
pub struct Cache<T: Storage> { pub struct Cache<T: Storage> {
svgs: HashMap<u64, Svg>, svgs: HashMap<u64, Svg>,
rasterized: HashMap<(u64, u32, u32), T::Entry>, rasterized: HashMap<(u64, u32, u32, Fill), T::Entry>,
svg_hits: HashSet<u64>, svg_hits: HashSet<u64>,
rasterized_hits: HashSet<(u64, u32, u32)>, rasterized_hits: HashSet<(u64, u32, u32, Fill)>,
} }
impl<T: Storage> Cache<T> { impl<T: Storage> Cache<T> {
@ -88,15 +90,18 @@ impl<T: Storage> Cache<T> {
(scale * height).ceil() as u32, (scale * height).ceil() as u32,
); );
let appearance = handle.appearance();
let fill = appearance.fill.map(crate::Color::into_rgba8);
// TODO: Optimize! // TODO: Optimize!
// We currently rerasterize the SVG when its size changes. This is slow // We currently rerasterize the SVG when its size changes. This is slow
// as heck. A GPU rasterizer like `pathfinder` may perform better. // as heck. A GPU rasterizer like `pathfinder` may perform better.
// It would be cool to be able to smooth resize the `svg` example. // It would be cool to be able to smooth resize the `svg` example.
if self.rasterized.contains_key(&(id, width, height)) { if self.rasterized.contains_key(&(id, width, height, fill)) {
let _ = self.svg_hits.insert(id); let _ = self.svg_hits.insert(id);
let _ = self.rasterized_hits.insert((id, width, height)); let _ = self.rasterized_hits.insert((id, width, height, fill));
return self.rasterized.get(&(id, width, height)); return self.rasterized.get(&(id, width, height, fill));
} }
match self.load(handle) { match self.load(handle) {
@ -121,15 +126,28 @@ impl<T: Storage> Cache<T> {
img.as_mut(), img.as_mut(),
)?; )?;
let allocation = let mut rgba = img.take();
storage.upload(width, height, img.data(), state)?;
if let Some(color) = fill {
rgba.chunks_exact_mut(4).for_each(|rgba| {
if rgba[3] > 0 {
rgba[0] = color[0];
rgba[1] = color[1];
rgba[2] = color[2];
}
});
}
let allocation = storage.upload(width, height, &rgba, state)?;
log::debug!("allocating {} {}x{}", id, width, height); log::debug!("allocating {} {}x{}", id, width, height);
let _ = self.svg_hits.insert(id); let _ = self.svg_hits.insert(id);
let _ = self.rasterized_hits.insert((id, width, height)); let _ = self.rasterized_hits.insert((id, width, height, fill));
let _ = self.rasterized.insert((id, width, height), allocation); let _ = self
.rasterized
.insert((id, width, height, fill), allocation);
self.rasterized.get(&(id, width, height)) self.rasterized.get(&(id, width, height, fill))
} }
Svg::NotFound => None, Svg::NotFound => None,
} }

View file

@ -6,11 +6,14 @@ use std::hash::{Hash, Hasher as _};
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
pub use iced_style::svg::{Appearance, StyleSheet};
/// A handle of Svg data. /// A handle of Svg data.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Handle { pub struct Handle {
id: u64, id: u64,
data: Arc<Data>, data: Arc<Data>,
appearance: Appearance,
} }
impl Handle { impl Handle {
@ -36,6 +39,7 @@ impl Handle {
Handle { Handle {
id: hasher.finish(), id: hasher.finish(),
data: Arc::new(data), data: Arc::new(data),
appearance: Appearance::default(),
} }
} }
@ -48,6 +52,16 @@ impl Handle {
pub fn data(&self) -> &Data { pub fn data(&self) -> &Data {
&self.data &self.data
} }
/// Returns the styling [`Appearance`] for the SVG.
pub fn appearance(&self) -> Appearance {
self.appearance
}
/// Set the [`Appearance`] for the SVG.
pub fn set_appearance(&mut self, appearance: Appearance) {
self.appearance = appearance;
}
} }
impl Hash for Handle { impl Hash for Handle {

View file

@ -285,6 +285,12 @@ where
/// ///
/// [`Svg`]: widget::Svg /// [`Svg`]: widget::Svg
/// [`Handle`]: widget::svg::Handle /// [`Handle`]: widget::svg::Handle
pub fn svg(handle: impl Into<widget::svg::Handle>) -> widget::Svg { pub fn svg<Renderer>(
handle: impl Into<widget::svg::Handle>,
) -> widget::Svg<Renderer>
where
Renderer: crate::svg::Renderer,
Renderer::Theme: crate::svg::StyleSheet,
{
widget::Svg::new(handle) widget::Svg::new(handle)
} }

View file

@ -9,7 +9,7 @@ use crate::{
use std::path::PathBuf; use std::path::PathBuf;
pub use svg::Handle; pub use svg::{Handle, StyleSheet};
/// A vector graphics image. /// A vector graphics image.
/// ///
@ -17,15 +17,25 @@ pub use svg::Handle;
/// ///
/// [`Svg`] images can have a considerable rendering cost when resized, /// [`Svg`] images can have a considerable rendering cost when resized,
/// specially when they are complex. /// specially when they are complex.
#[derive(Debug, Clone)] #[derive(Clone)]
pub struct Svg { #[allow(missing_debug_implementations)]
pub struct Svg<Renderer>
where
Renderer: svg::Renderer,
Renderer::Theme: StyleSheet,
{
handle: Handle, handle: Handle,
width: Length, width: Length,
height: Length, height: Length,
content_fit: ContentFit, content_fit: ContentFit,
style: <Renderer::Theme as StyleSheet>::Style,
} }
impl Svg { impl<Renderer> Svg<Renderer>
where
Renderer: svg::Renderer,
Renderer::Theme: StyleSheet,
{
/// Creates a new [`Svg`] from the given [`Handle`]. /// Creates a new [`Svg`] from the given [`Handle`].
pub fn new(handle: impl Into<Handle>) -> Self { pub fn new(handle: impl Into<Handle>) -> Self {
Svg { Svg {
@ -33,22 +43,26 @@ impl Svg {
width: Length::Fill, width: Length::Fill,
height: Length::Shrink, height: Length::Shrink,
content_fit: ContentFit::Contain, content_fit: ContentFit::Contain,
style: Default::default(),
} }
} }
/// Creates a new [`Svg`] that will display the contents of the file at the /// Creates a new [`Svg`] that will display the contents of the file at the
/// provided path. /// provided path.
#[must_use]
pub fn from_path(path: impl Into<PathBuf>) -> Self { pub fn from_path(path: impl Into<PathBuf>) -> Self {
Self::new(Handle::from_path(path)) Self::new(Handle::from_path(path))
} }
/// Sets the width of the [`Svg`]. /// Sets the width of the [`Svg`].
#[must_use]
pub fn width(mut self, width: Length) -> Self { pub fn width(mut self, width: Length) -> Self {
self.width = width; self.width = width;
self self
} }
/// Sets the height of the [`Svg`]. /// Sets the height of the [`Svg`].
#[must_use]
pub fn height(mut self, height: Length) -> Self { pub fn height(mut self, height: Length) -> Self {
self.height = height; self.height = height;
self self
@ -57,17 +71,29 @@ impl Svg {
/// Sets the [`ContentFit`] of the [`Svg`]. /// Sets the [`ContentFit`] of the [`Svg`].
/// ///
/// Defaults to [`ContentFit::Contain`] /// Defaults to [`ContentFit::Contain`]
#[must_use]
pub fn content_fit(self, content_fit: ContentFit) -> Self { pub fn content_fit(self, content_fit: ContentFit) -> Self {
Self { Self {
content_fit, content_fit,
..self ..self
} }
} }
/// Sets the style variant of this [`Svg`].
#[must_use]
pub fn style(
mut self,
style: <Renderer::Theme as StyleSheet>::Style,
) -> Self {
self.style = style;
self
}
} }
impl<Message, Renderer> Widget<Message, Renderer> for Svg impl<Message, Renderer> Widget<Message, Renderer> for Svg<Renderer>
where where
Renderer: svg::Renderer, Renderer: svg::Renderer,
Renderer::Theme: iced_style::svg::StyleSheet,
{ {
fn width(&self) -> Length { fn width(&self) -> Length {
self.width self.width
@ -114,12 +140,15 @@ where
&self, &self,
_state: &Tree, _state: &Tree,
renderer: &mut Renderer, renderer: &mut Renderer,
_theme: &Renderer::Theme, theme: &Renderer::Theme,
_style: &renderer::Style, _style: &renderer::Style,
layout: Layout<'_>, layout: Layout<'_>,
_cursor_position: Point, _cursor_position: Point,
_viewport: &Rectangle, _viewport: &Rectangle,
) { ) {
let mut handle = self.handle.clone();
handle.set_appearance(theme.appearance(self.style));
let Size { width, height } = renderer.dimensions(&self.handle); let Size { width, height } = renderer.dimensions(&self.handle);
let image_size = Size::new(width as f32, height as f32); let image_size = Size::new(width as f32, height as f32);
@ -138,7 +167,7 @@ where
..bounds ..bounds
}; };
renderer.draw(self.handle.clone(), drawing_bounds + offset) renderer.draw(handle, drawing_bounds + offset);
}; };
if adjusted_fit.width > bounds.width if adjusted_fit.width > bounds.width
@ -146,16 +175,18 @@ where
{ {
renderer.with_layer(bounds, render); renderer.with_layer(bounds, render);
} else { } else {
render(renderer) render(renderer);
} }
} }
} }
impl<'a, Message, Renderer> From<Svg> for Element<'a, Message, Renderer> impl<'a, Message, Renderer> From<Svg<Renderer>>
for Element<'a, Message, Renderer>
where where
Renderer: svg::Renderer, Renderer: svg::Renderer + 'a,
Renderer::Theme: iced_style::svg::StyleSheet,
{ {
fn from(icon: Svg) -> Element<'a, Message, Renderer> { fn from(icon: Svg<Renderer>) -> Element<'a, Message, Renderer> {
Element::new(icon) Element::new(icon)
} }
} }

View file

@ -32,6 +32,7 @@ pub mod radio;
pub mod rule; pub mod rule;
pub mod scrollable; pub mod scrollable;
pub mod slider; pub mod slider;
pub mod svg;
pub mod text; pub mod text;
pub mod text_input; pub mod text_input;
pub mod theme; pub mod theme;

21
style/src/svg.rs Normal file
View file

@ -0,0 +1,21 @@
//! Change the appearance of a svg.
use iced_core::Color;
/// The appearance of a svg.
#[derive(Debug, Default, Clone, Copy)]
pub struct Appearance {
/// Changes the fill color
///
/// Useful for coloring a symbolic icon.
pub fill: Option<Color>,
}
/// The stylesheet of a svg.
pub trait StyleSheet {
/// The supported style of the [`StyleSheet`].
type Style: Default + Copy;
/// Produces the [`Appearance`] of the svg.
fn appearance(&self, style: Self::Style) -> Appearance;
}

View file

@ -16,6 +16,7 @@ use crate::radio;
use crate::rule; use crate::rule;
use crate::scrollable; use crate::scrollable;
use crate::slider; use crate::slider;
use crate::svg;
use crate::text; use crate::text;
use crate::text_input; use crate::text_input;
use crate::toggler; use crate::toggler;
@ -797,6 +798,29 @@ impl From<fn(&Theme) -> rule::Appearance> for Rule {
} }
} }
/**
* SVG
*/
#[derive(Default, Clone, Copy)]
pub enum Svg {
/// No filtering to the rendered SVG.
#[default]
Default,
/// Apply custom filtering to the SVG.
Custom(fn(&Theme) -> svg::Appearance),
}
impl svg::StyleSheet for Theme {
type Style = Svg;
fn appearance(&self, style: Self::Style) -> svg::Appearance {
match style {
Svg::Default => Default::default(),
Svg::Custom(appearance) => appearance(self),
}
}
}
impl rule::StyleSheet for Theme { impl rule::StyleSheet for Theme {
type Style = Rule; type Style = Rule;