Skip to content

Instantly share code, notes, and snippets.

@juancampa
Created March 31, 2023 17:43
Show Gist options
  • Save juancampa/d8dcf7cdab813062f082eac7415abcfc to your computer and use it in GitHub Desktop.
Save juancampa/d8dcf7cdab813062f082eac7415abcfc to your computer and use it in GitHub Desktop.
Egui inner shadow
#[extension_trait]
pub impl UiExt for Ui {
fn inner_shadow_top(&mut self, mut avail_rect: Rect, opacity: f32) {
let painter = self.painter();
avail_rect.set_height(1.0);
const STEPS: usize = 8;
for i in 0..STEPS {
let alpha = 1.0 - (i as f32 / STEPS as f32);
let shift = avail_rect.height() * i as f32;
let rect = avail_rect.translate((0.0, shift).into());
painter.rect_filled(rect, 0.0, Color32::from_black_alpha((alpha * alpha * 70.0 * opacity).floor() as u8));
}
}
fn inner_shadow_bottom(&mut self, avail_rect: Rect, opacity: f32) {
let painter = self.painter();
let mut avail_rect = avail_rect.translate((0.0, avail_rect.height() - 1.0).into());
avail_rect.set_height(1.0);
const STEPS: usize = 8;
for i in 0..STEPS {
let alpha = 1.0 - (i as f32 / STEPS as f32);
let shift = -avail_rect.height() * i as f32;
let rect = avail_rect.translate((0.0, shift).into());
painter.rect_filled(rect, 0.0, Color32::from_black_alpha((alpha * alpha * 80.0 * opacity).floor() as u8));
}
}
}
#[extension_trait]
pub impl<T> ScrollAreaOutputExt for ScrollAreaOutput<T> {
fn inner_shadow(self, ui: &mut Ui) -> Self {
const RAMP: f32 = 12.0;
let mut shadow_rect = self.inner_rect;
shadow_rect.set_width(shadow_rect.width() + ui.spacing().scroll_bar_inner_margin);
let opacity = self.state.offset.y.min(RAMP).max(0.0) / RAMP;
ui.inner_shadow_top(shadow_rect, opacity);
let opacity = (self.content_size.y - self.state.offset.y - self.inner_rect.height()).min(RAMP).max(0.0) / RAMP;
ui.inner_shadow_bottom(shadow_rect, opacity);
self
}
}
egui::ScrollArea::vertical()
.auto_shrink([false, false])
.show(ui, |ui| {
// Contents here
})
.inner_shadow(ui); // <--------------- Shadows added here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment