Skip to main content

cranpose_ui/widgets/
canvas.rs

1//! Canvas composable for custom drawing via [`DrawScope`].
2//!
3//! Matches Jetpack Compose's `Canvas(modifier) { onDraw }`.
4
5use cranpose_core::NodeId;
6use cranpose_ui_graphics::{DrawScope, Size};
7
8use crate::{composable, layout::policies::LeafMeasurePolicy, modifier::Modifier, widgets::Layout};
9
10/// Draws custom content through a [`DrawScope`]. The modifier sets canvas bounds.
11/// The draw scope also measures and draws text with the app's fonts.
12///
13/// # Example
14///
15/// ```rust
16/// use cranpose_ui::*;
17///
18/// #[composable]
19/// fn ColorPanel() {
20///     Canvas(Modifier::empty().size_points(200.0, 100.0), |scope| {
21///         scope.draw_rect(Brush::solid(Color::RED));
22///     });
23/// }
24/// ```
25///
26/// For text, use `DrawTextStyle`, `DrawScope::measure_text` and
27/// `DrawScope::draw_text_from` to place a label within the canvas.
28#[composable]
29pub fn Canvas(modifier: Modifier, on_draw: impl Fn(&mut dyn DrawScope) + 'static) -> NodeId {
30    let draw_modifier = modifier.draw_behind(on_draw);
31    Layout(draw_modifier, LeafMeasurePolicy::new(Size::ZERO), || {})
32}
33
34#[cfg(test)]
35#[path = "tests/canvas_tests.rs"]
36mod tests;