Skip to main content

cranpose_ui/modifier/
draw_cache.rs

1use std::rc::Rc;
2
3use cranpose_ui_graphics::{DrawScope, DrawScopeDefault};
4
5use super::{DrawCacheBuilder, DrawCommand, Modifier};
6use crate::modifier_nodes::DrawCommandElement;
7
8impl Modifier {
9    /// Draw around content.
10    ///
11    /// The callback runs once when the modifier is recorded. Its last
12    /// `draw_content()` call splits drawing into behind (before) and overlay
13    /// (after) phases. With no `draw_content()` call, all primitives draw as
14    /// overlay content.
15    ///
16    /// Example: `Modifier::empty().draw_with_content(|scope| { ... })`
17    pub fn draw_with_content(self, f: impl Fn(&mut dyn DrawScope) + 'static) -> Self {
18        let func = Rc::new(move |scope: &mut DrawScopeDefault| f(scope));
19        let modifier = Self::with_element(DrawCommandElement::new(DrawCommand::WithContent(func)));
20        self.then(modifier)
21    }
22
23    /// Draw content behind.
24    ///
25    /// Example: `Modifier::empty().draw_behind(|scope| { ... })`
26    pub fn draw_behind(self, f: impl Fn(&mut dyn DrawScope) + 'static) -> Self {
27        let func = Rc::new(move |scope: &mut DrawScopeDefault| f(scope));
28        let modifier = Self::with_element(DrawCommandElement::new(DrawCommand::Behind(func)));
29        self.then(modifier)
30    }
31
32    /// Draw with cache.
33    ///
34    /// Example: `Modifier::empty().draw_with_cache(|builder| { ... })`
35    pub fn draw_with_cache(self, build: impl FnOnce(&mut DrawCacheBuilder)) -> Self {
36        let mut builder = DrawCacheBuilder::default();
37        build(&mut builder);
38        let commands = builder.finish();
39        let modifier = Self::with_element(DrawCommandElement::from_commands(commands));
40        self.then(modifier)
41    }
42}