Skip to content

Commit

Permalink
Merge pull request #1578 from iced-rs/svg-styling
Browse files Browse the repository at this point in the history
Svg styling
  • Loading branch information
hecrj authored Dec 6, 2022
2 parents 28f0bee + f99d24e commit f38e7fc
Show file tree
Hide file tree
Showing 16 changed files with 255 additions and 53 deletions.
21 changes: 17 additions & 4 deletions core/src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,17 @@ impl Color {
}
}

/// Converts the [`Color`] into its RGBA8 equivalent.
#[must_use]
pub fn into_rgba8(self) -> [u8; 4] {
[
(self.r * 255.0).round() as u8,
(self.g * 255.0).round() as u8,
(self.b * 255.0).round() as u8,
(self.a * 255.0).round() as u8,
]
}

/// Converts the [`Color`] into its linear values.
pub fn into_linear(self) -> [f32; 4] {
// As described in:
Expand Down Expand Up @@ -148,24 +159,26 @@ impl From<[f32; 4]> for Color {
#[macro_export]
macro_rules! color {
($r:expr, $g:expr, $b:expr) => {
Color::from_rgb8($r, $g, $b)
$crate::Color::from_rgb8($r, $g, $b)
};
($r:expr, $g:expr, $b:expr, $a:expr) => {
Color::from_rgba8($r, $g, $b, $a)
$crate::Color::from_rgba8($r, $g, $b, $a)
};
($hex:expr) => {{
let hex = $hex as u32;
let r = (hex & 0xff0000) >> 16;
let g = (hex & 0xff00) >> 8;
let b = (hex & 0xff);
Color::from_rgb8(r as u8, g as u8, b as u8)

$crate::Color::from_rgb8(r as u8, g as u8, b as u8)
}};
($hex:expr, $a:expr) => {{
let hex = $hex as u32;
let r = (hex & 0xff0000) >> 16;
let g = (hex & 0xff00) >> 8;
let b = (hex & 0xff);
Color::from_rgba8(r as u8, g as u8, b as u8, $a)

$crate::Color::from_rgba8(r as u8, g as u8, b as u8, $a)
}};
}

Expand Down
71 changes: 54 additions & 17 deletions examples/svg/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,39 +1,76 @@
use iced::widget::{container, svg};
use iced::{Element, Length, Sandbox, Settings};
use iced::theme;
use iced::widget::{checkbox, column, container, svg};
use iced::{color, Element, Length, Sandbox, Settings};

pub fn main() -> iced::Result {
Tiger::run(Settings::default())
}

struct Tiger;
#[derive(Debug, Default)]
struct Tiger {
apply_color_filter: bool,
}

#[derive(Debug, Clone, Copy)]
pub enum Message {
ToggleColorFilter(bool),
}

impl Sandbox for Tiger {
type Message = ();
type Message = Message;

fn new() -> Self {
Tiger
Tiger::default()
}

fn title(&self) -> String {
String::from("SVG - Iced")
}

fn update(&mut self, _message: ()) {}
fn update(&mut self, message: Self::Message) {
match message {
Message::ToggleColorFilter(apply_color_filter) => {
self.apply_color_filter = apply_color_filter;
}
}
}

fn view(&self) -> Element<()> {
let svg = svg(svg::Handle::from_path(format!(
fn view(&self) -> Element<Self::Message> {
let handle = svg::Handle::from_path(format!(
"{}/resources/tiger.svg",
env!("CARGO_MANIFEST_DIR")
)))
.width(Length::Fill)
.height(Length::Fill);
));

let svg = svg(handle).width(Length::Fill).height(Length::Fill).style(
if self.apply_color_filter {
theme::Svg::custom_fn(|_theme| svg::Appearance {
color: Some(color!(0x0000ff)),
})
} else {
theme::Svg::Default
},
);

container(svg)
let apply_color_filter = checkbox(
"Apply a color filter",
self.apply_color_filter,
Message::ToggleColorFilter,
);

container(
column![
svg,
container(apply_color_filter).width(Length::Fill).center_x()
]
.spacing(20)
.width(Length::Fill)
.height(Length::Fill)
.padding(20)
.center_x()
.center_y()
.into()
.height(Length::Fill),
)
.width(Length::Fill)
.height(Length::Fill)
.padding(20)
.center_x()
.center_y()
.into()
}
}
7 changes: 6 additions & 1 deletion glow/src/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,11 +172,16 @@ impl Pipeline {
layer::Image::Raster { handle: _, bounds } => (None, bounds),

#[cfg(feature = "svg")]
layer::Image::Vector { handle, bounds } => {
layer::Image::Vector {
handle,
color,
bounds,
} => {
let size = [bounds.width, bounds.height];
(
vector_cache.upload(
handle,
*color,
size,
_scale_factor,
&mut gl,
Expand Down
38 changes: 28 additions & 10 deletions graphics/src/image/vector.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Vector image loading and caching
use crate::image::Storage;
use crate::Color;

use iced_native::svg;
use iced_native::Size;
Expand Down Expand Up @@ -33,11 +34,13 @@ impl Svg {
#[derive(Debug)]
pub struct Cache<T: Storage> {
svgs: HashMap<u64, Svg>,
rasterized: HashMap<(u64, u32, u32), T::Entry>,
rasterized: HashMap<(u64, u32, u32, ColorFilter), T::Entry>,
svg_hits: HashSet<u64>,
rasterized_hits: HashSet<(u64, u32, u32)>,
rasterized_hits: HashSet<(u64, u32, u32, ColorFilter)>,
}

type ColorFilter = Option<[u8; 4]>;

impl<T: Storage> Cache<T> {
/// Load svg
pub fn load(&mut self, handle: &svg::Handle) -> &Svg {
Expand Down Expand Up @@ -76,6 +79,7 @@ impl<T: Storage> Cache<T> {
pub fn upload(
&mut self,
handle: &svg::Handle,
color: Option<Color>,
[width, height]: [f32; 2],
scale: f32,
state: &mut T::State<'_>,
Expand All @@ -88,15 +92,18 @@ impl<T: Storage> Cache<T> {
(scale * height).ceil() as u32,
);

let color = color.map(Color::into_rgba8);
let key = (id, width, height, color);

// TODO: Optimize!
// We currently rerasterize the SVG when its size changes. This is slow
// as heck. A GPU rasterizer like `pathfinder` may perform better.
// 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(&key) {
let _ = self.svg_hits.insert(id);
let _ = self.rasterized_hits.insert((id, width, height));
let _ = self.rasterized_hits.insert(key);

return self.rasterized.get(&(id, width, height));
return self.rasterized.get(&key);
}

match self.load(handle) {
Expand All @@ -121,15 +128,26 @@ impl<T: Storage> Cache<T> {
img.as_mut(),
)?;

let allocation =
storage.upload(width, height, img.data(), state)?;
let mut rgba = img.take();

if let Some(color) = color {
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);

let _ = self.svg_hits.insert(id);
let _ = self.rasterized_hits.insert((id, width, height));
let _ = self.rasterized.insert((id, width, height), allocation);
let _ = self.rasterized_hits.insert(key);
let _ = self.rasterized.insert(key, allocation);

self.rasterized.get(&(id, width, height))
self.rasterized.get(&key)
}
Svg::NotFound => None,
}
Expand Down
7 changes: 6 additions & 1 deletion graphics/src/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,11 +251,16 @@ impl<'a> Layer<'a> {
bounds: *bounds + translation,
});
}
Primitive::Svg { handle, bounds } => {
Primitive::Svg {
handle,
color,
bounds,
} => {
let layer = &mut layers[current_layer];

layer.images.push(Image::Vector {
handle: handle.clone(),
color: *color,
bounds: *bounds + translation,
});
}
Expand Down
6 changes: 5 additions & 1 deletion graphics/src/layer/image.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::Rectangle;
use crate::{Color, Rectangle};

use iced_native::{image, svg};

/// A raster or vector image.
Expand All @@ -17,6 +18,9 @@ pub enum Image {
/// The handle of a vector image.
handle: svg::Handle,

/// The [`Color`] filter
color: Option<Color>,

/// The bounds of the image.
bounds: Rectangle,
},
Expand Down
3 changes: 3 additions & 0 deletions graphics/src/primitive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ pub enum Primitive {
/// The path of the SVG file
handle: svg::Handle,

/// The [`Color`] filter
color: Option<Color>,

/// The bounds of the viewport
bounds: Rectangle,
},
Expand Down
15 changes: 12 additions & 3 deletions graphics/src/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use iced_native::layout;
use iced_native::renderer;
use iced_native::svg;
use iced_native::text::{self, Text};
use iced_native::{Background, Element, Font, Point, Rectangle, Size};
use iced_native::{Background, Color, Element, Font, Point, Rectangle, Size};

pub use iced_native::renderer::Style;

Expand Down Expand Up @@ -200,7 +200,16 @@ where
self.backend().viewport_dimensions(handle)
}

fn draw(&mut self, handle: svg::Handle, bounds: Rectangle) {
self.draw_primitive(Primitive::Svg { handle, bounds })
fn draw(
&mut self,
handle: svg::Handle,
color: Option<Color>,
bounds: Rectangle,
) {
self.draw_primitive(Primitive::Svg {
handle,
color,
bounds,
})
}
}
6 changes: 3 additions & 3 deletions native/src/svg.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! Load and draw vector graphics.
use crate::{Hasher, Rectangle, Size};
use crate::{Color, Hasher, Rectangle, Size};

use std::borrow::Cow;
use std::hash::{Hash, Hasher as _};
Expand Down Expand Up @@ -84,6 +84,6 @@ pub trait Renderer: crate::Renderer {
/// Returns the default dimensions of an SVG for the given [`Handle`].
fn dimensions(&self, handle: &Handle) -> Size<u32>;

/// Draws an SVG with the given [`Handle`] and inside the provided `bounds`.
fn draw(&mut self, handle: Handle, bounds: Rectangle);
/// Draws an SVG with the given [`Handle`], an optional [`Color`] filter, and inside the provided `bounds`.
fn draw(&mut self, handle: Handle, color: Option<Color>, bounds: Rectangle);
}
8 changes: 7 additions & 1 deletion native/src/widget/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,12 @@ where
///
/// [`Svg`]: widget::Svg
/// [`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: widget::svg::StyleSheet,
{
widget::Svg::new(handle)
}
Loading

0 comments on commit f38e7fc

Please sign in to comment.