Skip to content

Commit

Permalink
Add opacity and multiply_opacity functions to Ui and Painter (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
emilk authored May 30, 2024
1 parent a7eed0a commit 6282844
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
25 changes: 24 additions & 1 deletion crates/egui/src/painter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
19 changes: 18 additions & 1 deletion crates/egui/src/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
/// ```
Expand All @@ -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 {
Expand Down

0 comments on commit 6282844

Please sign in to comment.