Skip to content

The window doesn't become transparent for the fade effect #5765

@polarker

Description

@polarker

The window should fade to transparent after 2 seconds, but it's becoming opaque instead.

Image

Here is the source code to produce:

Source Code
use eframe::egui;
use std::time::Instant;

fn main() -> eframe::Result<()> {
    let options = eframe::NativeOptions {
        viewport: egui::ViewportBuilder::default()
            .with_inner_size([320.0, 240.0])
            .with_transparent(true),
        ..Default::default()
    };

    eframe::run_native(
        "Fade Window",
        options,
        Box::new(move |cc| {
            let mut app = MyApp::new();
            Box::new(app)
        }),
    )
}

struct MyApp {
    start_time: Instant,
    opacity: f32,
    fade_duration: f32,
}

impl MyApp {
    fn new() -> Self {
        Self {
            start_time: Instant::now(),
            opacity: 1.0,
            fade_duration: 2.0, // Duration of fade in seconds
        }
    }
}

impl eframe::App for MyApp {
    fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] {
        [0.0, 0.0, 0.0, 0.0]
    }

    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        // Request repaint after a short interval for smooth animation
        ctx.request_repaint_after(std::time::Duration::from_millis(16)); // ~60 FPS

        // Check if 3 seconds have passed
        if self.start_time.elapsed().as_secs_f32() >= self.fade_duration {
            // Calculate fade progress
            let fade_progress =
                (self.start_time.elapsed().as_secs_f32() - self.fade_duration) / self.fade_duration;
            if fade_progress >= 1.0 {
                self.opacity = 0.0;
            } else {
                self.opacity = 1.0 - fade_progress;
            }
        }

        println!(
            "opacity: {}, {}",
            self.opacity,
            (self.opacity * 255.0) as u8
        );

        let panel_frame = egui::Frame::default().fill(egui::Color32::from_rgba_unmultiplied(
            0,
            0,
            0,
            (self.opacity * 255.0) as u8,
        ));
        // Show panel with current opacity
        egui::CentralPanel::default()
            .frame(panel_frame)
            .show(ctx, |ui| {
                ui.label("Hello, world!");
            });
    }
}

However, if I set the panel to be transparent from the start, without fading, the window is transparent as expected.

        let panel_frame = egui::Frame::default().fill(egui::Color32::from_rgba_unmultiplied(
            0, 0, 0, 0,
            // (self.opacity * 255.0) as u8,
        ));
Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions