From 6282844f65566f1a982fe2f0a970188184beefd1 Mon Sep 17 00:00:00 2001 From: Emil Ernerfeldt Date: Thu, 30 May 2024 16:07:42 +0200 Subject: [PATCH] Add `opacity` and `multiply_opacity` functions to `Ui` and `Painter` (#4586) --- crates/egui/src/painter.rs | 25 ++++++++++++++++++++++++- crates/egui/src/ui.rs | 19 ++++++++++++++++++- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/crates/egui/src/painter.rs b/crates/egui/src/painter.rs index 0935587cc..534524e32 100644 --- a/crates/egui/src/painter.rs +++ b/crates/egui/src/painter.rs @@ -83,12 +83,35 @@ impl Painter { self.fade_to_color = fade_to_color; } - pub(crate) fn set_opacity(&mut self, opacity: f32) { + /// Set the opacity (alpha multiplier) of everything painted by this painter from this point forward. + /// + /// `opacity` must be between 0.0 and 1.0, where 0.0 means fully transparent (i.e., invisible) + /// and 1.0 means fully opaque. + /// + /// See also: [`Self::opacity`] and [`Self::multiply_opacity`]. + pub fn set_opacity(&mut self, opacity: f32) { if opacity.is_finite() { self.opacity_factor = opacity.clamp(0.0, 1.0); } } + /// Like [`Self::set_opacity`], but multiplies the given value with the current opacity. + /// + /// See also: [`Self::set_opacity`] and [`Self::opacity`]. + pub fn multiply_opacity(&mut self, opacity: f32) { + if opacity.is_finite() { + self.opacity_factor *= opacity.clamp(0.0, 1.0); + } + } + + /// Read the current opacity of the underlying painter. + /// + /// See also: [`Self::set_opacity`] and [`Self::multiply_opacity`]. + #[inline] + pub fn opacity(&self) -> f32 { + self.opacity_factor + } + pub(crate) fn is_visible(&self) -> bool { self.fade_to_color != Some(Color32::TRANSPARENT) } diff --git a/crates/egui/src/ui.rs b/crates/egui/src/ui.rs index 40ffea831..94cfb638b 100644 --- a/crates/egui/src/ui.rs +++ b/crates/egui/src/ui.rs @@ -341,7 +341,7 @@ impl Ui { /// Make the widget in this [`Ui`] semi-transparent. /// /// `opacity` must be between 0.0 and 1.0, where 0.0 means fully transparent (i.e., invisible) - /// and 1.0 means fully opaque (i.e., the same as not calling the method at all). + /// and 1.0 means fully opaque. /// /// ### Example /// ``` @@ -354,10 +354,27 @@ impl Ui { /// }); /// # }); /// ``` + /// + /// See also: [`Self::opacity`] and [`Self::multiply_opacity`]. pub fn set_opacity(&mut self, opacity: f32) { self.painter.set_opacity(opacity); } + /// Like [`Self::set_opacity`], but multiplies the given value with the current opacity. + /// + /// See also: [`Self::set_opacity`] and [`Self::opacity`]. + pub fn multiply_opacity(&mut self, opacity: f32) { + self.painter.multiply_opacity(opacity); + } + + /// Read the current opacity of the underlying painter. + /// + /// See also: [`Self::set_opacity`] and [`Self::multiply_opacity`]. + #[inline] + pub fn opacity(&self) -> f32 { + self.painter.opacity() + } + /// Read the [`Layout`]. #[inline] pub fn layout(&self) -> &Layout {