Implement SVG rendering

This commit is contained in:
Antonio Scandurra
2021-04-06 13:46:33 +02:00
parent 2970e934da
commit e0c43dac25
9 changed files with 505 additions and 49 deletions
+15 -1
View File
@@ -1,5 +1,5 @@
use anyhow::{anyhow, Result};
use std::borrow::Cow;
use std::{borrow::Cow, cell::RefCell, collections::HashMap};
pub trait AssetSource: 'static {
fn load(&self, path: &str) -> Result<Cow<[u8]>>;
@@ -16,12 +16,26 @@ impl AssetSource for () {
pub struct AssetCache {
source: Box<dyn AssetSource>,
svgs: RefCell<HashMap<String, usvg::Tree>>,
}
impl AssetCache {
pub fn new(source: impl AssetSource) -> Self {
Self {
source: Box::new(source),
svgs: RefCell::new(HashMap::new()),
}
}
pub fn svg(&self, path: &str) -> Result<usvg::Tree> {
let mut svgs = self.svgs.borrow_mut();
if let Some(svg) = svgs.get(path) {
Ok(svg.clone())
} else {
let bytes = self.source.load(path)?;
let svg = usvg::Tree::from_data(&bytes, &usvg::Options::default())?;
svgs.insert(path.to_string(), svg.clone());
Ok(svg)
}
}
}