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 around content.
8    ///
9    /// `draw_content()` splits drawing into behind (before) and overlay (after)
10    /// phases. If `draw_content()` is never called, primitives are treated as
11    /// overlay for backward compatibility.
12    ///
13    /// Example: `Modifier::empty().draw_with_content(|scope| { ... })`
14    pub fn draw_with_content(self, f: impl Fn(&mut dyn DrawScope) + 'static) -> Self {
15        let func = Rc::new(move |size: Size| {
16            let mut scope = DrawScopeDefault::new(size);
17            f(&mut scope);
18            scope.into_primitives()
19        });
20        let modifier = Self::with_element(DrawCommandElement::new(DrawCommand::WithContent(
21            func.clone(),
22        )));
23        self.then(modifier)
24    }
25
26    /// Draw content behind.
27    ///
28    /// Example: `Modifier::empty().draw_behind(|scope| { ... })`
29    pub fn draw_behind(self, f: impl Fn(&mut dyn DrawScope) + 'static) -> Self {
30        let func = Rc::new(move |size: Size| {
31            let mut scope = DrawScopeDefault::new(size);
32            f(&mut scope);
33            scope.into_primitives()
34        });
35        let modifier =
36            Self::with_element(DrawCommandElement::new(DrawCommand::Behind(func.clone())));
37        self.then(modifier)
38    }
39
40    /// Draw with cache.
41    ///
42    /// Example: `Modifier::empty().draw_with_cache(|builder| { ... })`
43    pub fn draw_with_cache(self, build: impl FnOnce(&mut DrawCacheBuilder)) -> Self {
44        let mut builder = DrawCacheBuilder::default();
45        build(&mut builder);
46        let commands = builder.finish();
47        let modifier = Self::with_element(DrawCommandElement::from_commands(commands));
48        self.then(modifier)
49    }
50}