|
| 1 | +#![deny(missing_docs)] |
| 2 | + |
| 3 | +use floem_reactive::{create_tracker, SignalTracker}; |
| 4 | +use peniko::kurbo::Size; |
| 5 | + |
| 6 | +use crate::{context::PaintCx, id::ViewId, view::View}; |
| 7 | + |
| 8 | +/// A canvas view |
| 9 | +#[allow(clippy::type_complexity)] |
| 10 | +pub struct Canvas { |
| 11 | + id: ViewId, |
| 12 | + paint_fn: Box<dyn Fn(&mut PaintCx, Size)>, |
| 13 | + size: Size, |
| 14 | + tracker: Option<SignalTracker>, |
| 15 | +} |
| 16 | + |
| 17 | +/// Creates a new Canvas view that can be used for custom painting |
| 18 | +/// |
| 19 | +/// A [`Canvas`] provides a low-level interface for custom drawing operations. The supplied |
| 20 | +/// paint function will be called whenever the view needs to be rendered, and any signals accessed |
| 21 | +/// within the paint function will automatically trigger repaints when they change. |
| 22 | +/// |
| 23 | +/// |
| 24 | +/// # Example |
| 25 | +/// ```rust |
| 26 | +/// use floem::prelude::*; |
| 27 | +/// use palette::css; |
| 28 | +/// use peniko::kurbo::Rect; |
| 29 | +/// canvas(move |cx, size| { |
| 30 | +/// cx.fill( |
| 31 | +/// &Rect::ZERO |
| 32 | +/// .with_size(size) |
| 33 | +/// .to_rounded_rect(8.), |
| 34 | +/// css::PURPLE, |
| 35 | +/// 0., |
| 36 | +/// ); |
| 37 | +/// }) |
| 38 | +/// .style(|s| s.size(100, 300)); |
| 39 | +/// ``` |
| 40 | +pub fn canvas(paint: impl Fn(&mut PaintCx, Size) + 'static) -> Canvas { |
| 41 | + let id = ViewId::new(); |
| 42 | + |
| 43 | + Canvas { |
| 44 | + id, |
| 45 | + paint_fn: Box::new(paint), |
| 46 | + size: Default::default(), |
| 47 | + tracker: None, |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl View for Canvas { |
| 52 | + fn id(&self) -> ViewId { |
| 53 | + self.id |
| 54 | + } |
| 55 | + |
| 56 | + fn debug_name(&self) -> std::borrow::Cow<'static, str> { |
| 57 | + "Canvas".into() |
| 58 | + } |
| 59 | + |
| 60 | + fn compute_layout( |
| 61 | + &mut self, |
| 62 | + _cx: &mut crate::context::ComputeLayoutCx, |
| 63 | + ) -> Option<peniko::kurbo::Rect> { |
| 64 | + self.size = self.id.get_size().unwrap_or_default(); |
| 65 | + None |
| 66 | + } |
| 67 | + |
| 68 | + fn paint(&mut self, cx: &mut PaintCx) { |
| 69 | + let id = self.id; |
| 70 | + let paint = &self.paint_fn; |
| 71 | + |
| 72 | + if self.tracker.is_none() { |
| 73 | + self.tracker = Some(create_tracker(move || { |
| 74 | + id.request_paint(); |
| 75 | + })); |
| 76 | + } |
| 77 | + |
| 78 | + let tracker = self.tracker.as_ref().unwrap(); |
| 79 | + tracker.track(|| { |
| 80 | + paint(cx, self.size); |
| 81 | + }); |
| 82 | + } |
| 83 | +} |
0 commit comments