From 45fe192f75946f98a6e1d6e418f17d055633e1cd Mon Sep 17 00:00:00 2001 From: kernelkind Date: Tue, 15 Apr 2025 18:37:38 -0400 Subject: [PATCH] introduce `ImagePulseTint` Signed-off-by: kernelkind --- crates/notedeck_ui/src/anim.rs | 71 ++++++++++++++++++++++++++++++++++ crates/notedeck_ui/src/lib.rs | 2 +- 2 files changed, 72 insertions(+), 1 deletion(-) diff --git a/crates/notedeck_ui/src/anim.rs b/crates/notedeck_ui/src/anim.rs index 94007d9e..203a7411 100644 --- a/crates/notedeck_ui/src/anim.rs +++ b/crates/notedeck_ui/src/anim.rs @@ -138,3 +138,74 @@ impl AnimationHelper { min_object_size + ((max_object_size - min_object_size) * self.animation_progress) } } + +pub struct ImagePulseTint<'a> { + ctx: &'a egui::Context, + id: egui::Id, + image: egui::Image<'a>, + color_unmultiplied: &'a [u8; 3], + alpha_min: u8, + alpha_max: u8, + animation_speed: f32, +} + +impl<'a> ImagePulseTint<'a> { + pub fn new( + ctx: &'a egui::Context, + id: egui::Id, + image: egui::Image<'a>, + color_unmultiplied: &'a [u8; 3], + alpha_min: u8, + alpha_max: u8, + ) -> Self { + Self { + ctx, + id, + image, + color_unmultiplied, + alpha_min, + alpha_max, + animation_speed: ANIM_SPEED, + } + } + + pub fn with_speed(mut self, speed: f32) -> Self { + self.animation_speed = speed; + self + } + + pub fn animate(self) -> egui::Image<'a> { + let pulse_direction = if let Some(pulse_dir) = self.ctx.data(|d| d.get_temp(self.id)) { + pulse_dir + } else { + self.ctx.data_mut(|d| d.insert_temp(self.id, false)); + false + }; + + let alpha_min_f32 = self.alpha_min as f32; + let target = if pulse_direction { + self.alpha_max as f32 - alpha_min_f32 + } else { + 0.0 + }; + + let cur_val = self + .ctx + .animate_value_with_time(self.id, target, self.animation_speed); + + if (target - cur_val).abs() < 0.5 { + self.ctx + .data_mut(|d| d.insert_temp(self.id, !pulse_direction)); + } + + let alpha = + (cur_val + alpha_min_f32).clamp(self.alpha_min as f32, self.alpha_max as f32) as u8; + + self.image.tint(egui::Color32::from_rgba_unmultiplied( + self.color_unmultiplied[0], + self.color_unmultiplied[1], + self.color_unmultiplied[2], + alpha, + )) + } +} diff --git a/crates/notedeck_ui/src/lib.rs b/crates/notedeck_ui/src/lib.rs index 3747426c..69600975 100644 --- a/crates/notedeck_ui/src/lib.rs +++ b/crates/notedeck_ui/src/lib.rs @@ -6,5 +6,5 @@ pub mod icons; pub mod images; pub mod profile; -pub use anim::AnimationHelper; +pub use anim::{AnimationHelper, ImagePulseTint}; pub use profile::ProfilePic;