Path: blob/main/crates/bevy_dev_tools/src/easy_screenshot.rs
7219 views
use std::time::{SystemTime, UNIX_EPOCH};12use bevy_app::{App, Plugin, Update};3use bevy_ecs::prelude::*;4use bevy_input::{common_conditions::input_just_pressed, keyboard::KeyCode};5use bevy_render::view::screenshot::{save_to_disk, Screenshot};6use bevy_window::{PrimaryWindow, Window};78/// File format the screenshot will be saved in9#[derive(Clone, Copy)]10pub enum ScreenshotFormat {11/// JPEG format12Jpeg,13/// PNG format14Png,15/// BMP format16Bmp,17}1819/// Add this plugin to your app to enable easy screenshotting.20///21/// Add this plugin, press the key, and you have a screenshot 🎉22pub struct EasyScreenshotPlugin {23/// Key that will trigger a screenshot24pub trigger: KeyCode,25/// Format of the screenshot26///27/// The corresponding image format must be supported by bevy renderer28pub format: ScreenshotFormat,29}3031impl Default for EasyScreenshotPlugin {32fn default() -> Self {33EasyScreenshotPlugin {34trigger: KeyCode::PrintScreen,35format: ScreenshotFormat::Png,36}37}38}3940impl Plugin for EasyScreenshotPlugin {41fn build(&self, app: &mut App) {42let format = self.format;43app.add_systems(44Update,45(move |mut commands: Commands, window: Single<&Window, With<PrimaryWindow>>| {46let since_the_epoch = SystemTime::now()47.duration_since(UNIX_EPOCH)48.expect("time should go forward");4950commands51.spawn(Screenshot::primary_window())52.observe(save_to_disk(format!(53"{}-{}.{}",54window.title,55since_the_epoch.as_millis(),56match format {57ScreenshotFormat::Jpeg => "jpg",58ScreenshotFormat::Png => "png",59ScreenshotFormat::Bmp => "bmp",60}61)));62})63.run_if(input_just_pressed(self.trigger)),64);65}66}676869