Skip to main content

cranpose_ui/modifier/
draw_cache.rs

1use super::{DrawCacheBuilder, DrawCommand, Modifier, Size};
2use crate::modifier_nodes::DrawCommandElement;
3use cranpose_ui_graphics::{DrawScope, DrawScopeDefault};
4use std::rc::Rc;
5
6impl Modifier {
7    /// Draw content with overlay.
8    ///
9    /// Example: `Modifier::empty().draw_with_content(|scope| { ... })`
10    pub fn draw_with_content(self, f: impl Fn(&mut dyn DrawScope) + 'static) -> Self {
11        let func = Rc::new(move |size: Size| {
12            let mut scope = DrawScopeDefault::new(size);
13            f(&mut scope);
14            scope.into_primitives()
15        });
16        let modifier =
17            Self::with_element(DrawCommandElement::new(DrawCommand::Overlay(func.clone())));
18        self.then(modifier)
19    }
20
21    /// Draw content behind.
22    ///
23    /// Example: `Modifier::empty().draw_behind(|scope| { ... })`
24    pub fn draw_behind(self, f: impl Fn(&mut dyn DrawScope) + 'static) -> Self {
25        let func = Rc::new(move |size: Size| {
26            let mut scope = DrawScopeDefault::new(size);
27            f(&mut scope);
28            scope.into_primitives()
29        });
30        let modifier =
31            Self::with_element(DrawCommandElement::new(DrawCommand::Behind(func.clone())));
32        self.then(modifier)
33    }
34
35    /// Draw with cache.
36    ///
37    /// Example: `Modifier::empty().draw_with_cache(|builder| { ... })`
38    pub fn draw_with_cache(self, build: impl FnOnce(&mut DrawCacheBuilder)) -> Self {
39        let mut builder = DrawCacheBuilder::default();
40        build(&mut builder);
41        let commands = builder.finish();
42        let modifier = Self::with_element(DrawCommandElement::from_commands(commands));
43        self.then(modifier)
44    }
45}