Skip to main content

floem/views/
clip.rs

1#![deny(missing_docs)]
2
3use taffy::Overflow;
4
5use crate::{
6    style::Style,
7    view::{IntoView, View, ViewId},
8};
9
10/// A wrapper around a child View that clips painting so the child does not show outside of the viewport.
11///
12/// This can be useful for limiting child painting, including for rounded borders using border radius.
13pub struct Clip {
14    id: ViewId,
15}
16
17impl Clip {
18    /// Creates a new clip view wrapping the given child.
19    ///
20    /// ## Example
21    /// ```rust
22    /// use floem::views::{Clip, Label};
23    ///
24    /// let clipped = Clip::new(Label::new("Clipped content"));
25    /// ```
26    pub fn new(child: impl IntoView) -> Self {
27        let child = child.into_view();
28        let id = ViewId::new();
29        id.set_children([child]);
30        Clip { id }
31    }
32}
33
34/// A clip is a wrapper around a child View that will clip the painting of the child so that it does not show outside of the viewport of the [`Clip`].
35///
36/// This can be useful for limiting child painting, including for rounded borders using border radius.
37#[deprecated(since = "0.2.0", note = "Use Clip::new() instead")]
38pub fn clip<V: IntoView + 'static>(child: V) -> Clip {
39    Clip::new(child)
40}
41
42impl View for Clip {
43    fn id(&self) -> ViewId {
44        self.id
45    }
46
47    fn view_style(&self) -> Option<crate::style::Style> {
48        Some(
49            Style::new()
50                .overflow_x(Overflow::Clip)
51                .overflow_y(Overflow::Clip),
52        )
53    }
54
55    fn debug_name(&self) -> std::borrow::Cow<'static, str> {
56        "Clip".into()
57    }
58}
59
60/// A trait that adds a `clip` method to any type that implements `IntoView`.
61pub trait ClipExt {
62    /// Wrap the view in a clip view.
63    fn clip(self) -> Clip;
64}
65
66impl<T: IntoView + 'static> ClipExt for T {
67    fn clip(self) -> Clip {
68        Clip::new(self)
69    }
70}