Search code examples
rustbevy

How to add a window icon in Bevy?


I'm making a game in rust and I want it to be legit. Bevy ECS is great. I have been following tutorials and reading documentation, but there is this one thing I want to know. Can I change the window icon? If so, how?


Solution

  • It is not easy to do. You may see discussion of the problem here, and pr here and here. I am sure it will be solved in a nice standard way soon, meanwhile there is hacky way to do it described here

    use bevy::window::WindowId;
    use bevy::winit::WinitWindows;
    use winit::window::Icon;
    
    fn set_window_icon(
        // we have to use `NonSend` here
        windows: NonSend<WinitWindows>,
    ) {
        let primary = windows.get_window(WindowId::primary()).unwrap();
    
        // here we use the `image` crate to load our icon data from a png file
        // this is not a very bevy-native solution, but it will do
        let (icon_rgba, icon_width, icon_height) = {
            let image = image::open("my_icon.png")
                .expect("Failed to open icon path")
                .into_rgba8();
            let (width, height) = image.dimensions();
            let rgba = image.into_raw();
            (rgba, width, height)
        };
    
        let icon = Icon::from_rgba(icon_rgba, icon_width, icon_height).unwrap();
    
        primary.set_window_icon(Some(icon));
    }
    
    fn main() {
        App::new()
            .add_plugins(DefaultPlugins)
            .add_startup_system(set_window_icon)
            .run();
    }