mgui_core/render_object/
opacity.rs1use super::*;
2
3pub struct OpacityRenderObject {
5 pub child: Option<SharedRO>,
6 pub element_id: Option<ElementId>,
7 pub size: Size,
8 pub opacity: f32,
10}
11
12impl OpacityRenderObject {
13 pub fn new(child: Box<dyn RenderObject>, opacity: f32) -> Self {
14 Self {
15 child: Some(make_ro_shared(child)),
16 element_id: None,
17 size: Size::ZERO,
18 opacity: opacity.clamp(0.0, 1.0),
19 }
20 }
21 pub fn empty(opacity: f32) -> Self {
22 Self { child: None, element_id: None, size: Size::ZERO, opacity: opacity.clamp(0.0, 1.0) }
23 }
24}
25
26impl RenderObject for OpacityRenderObject {
27 fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
28 self.size = self.child.as_mut().map(|c| c.layout_cached(constraints, ctx)).unwrap_or(Size::ZERO);
29 self.size
30 }
31 fn paint(&self, _offset: Point, _painter: &mut PaintList) {
32 }
34 fn paint_as_layer_root(&self, offset: Point, painter: &mut PaintList) {
35 if let Some(c) = &self.child {
38 c.borrow().paint(offset, painter);
39 }
40 }
41 fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
42 if self.opacity <= 0.0 {
44 return None;
45 }
46 self.child.as_ref()?.borrow().hit_test(position, offset)
47 }
48 fn set_element_id(&mut self, _id: ElementId) {
49 }
51 fn child_slots(&self) -> Vec<(Point, SharedRO)> {
53 self.child.as_ref().map(|c| vec![(Point::ZERO, c.clone())]).unwrap_or_default()
54 }
55
56 fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
57 if let Some(c) = &self.child {
58 f(Point::ZERO, c);
59 }
60 }
61 fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
62 if let (Some(child_ro), Some(&cid)) = (self.child.as_mut(), child_ids.first()) {
63 if let Some(new_ro) = stateful_ros.first_mut() {
64 *child_ro = new_ro.clone();
65 }
66 child_ro.borrow_mut().set_element_id(cid);
67 }
68 }
69 fn content_size(&self) -> Size {
70 self.size
71 }
72 fn layer_layout_size(&self) -> Option<Size> {
73 Some(self.size)
74 }
75 fn push_child(&mut self, _offset: Point, _child: SharedRO) {
76 }
78 fn children_count(&self) -> usize {
79 if self.child.is_some() {
80 1
81 } else {
82 0
83 }
84 }
85 fn layer_effect(&self) -> crate::paint::LayerEffect {
86 crate::paint::LayerEffect::Opacity(self.opacity)
87 }
88
89 fn apply_state(&mut self, state: &mut dyn std::any::Any) -> StateApply {
95 let track_state = match state.downcast_ref::<crate::widget::animated::AnimatedOpacityState>() {
96 Some(s) => s,
97 None => return StateApply::Unsupported,
98 };
99 let next = track_state.presented_opacity().clamp(0.0, 1.0);
100 if (next - self.opacity).abs() < f32::EPSILON {
101 return StateApply::Unchanged;
102 }
103 self.opacity = next;
104 StateApply::Updated
105 }
106}