Skip to content

Instantly share code, notes, and snippets.

@spiderman-idog
Forked from DGriffin91/letterboxing.rs
Last active December 12, 2022 21:28
Show Gist options
  • Save spiderman-idog/fb244f6421f348dff9b0798aa35c04bd to your computer and use it in GitHub Desktop.
Save spiderman-idog/fb244f6421f348dff9b0798aa35c04bd to your computer and use it in GitHub Desktop.
Basic Letterboxing
// License: Apache-2.0 / MIT
use bevy::{
core_pipeline::clear_color::ClearColorConfig,
prelude::*,
render::{camera::RenderTarget, render_resource::*, view::RenderLayers},
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_startup_system(setup)
.run();
}
/// set up a simple 3D scene
fn setup(
mut commands: Commands,
mut images: ResMut<Assets<Image>>,
) {
// The size of the rendered area
let size = Extent3d {
width: 400,
height: 300,
..default()
};
// This is the texture that will be rendered to
let mut image = Image {
texture_descriptor: TextureDescriptor {
label: None,
size,
dimension: TextureDimension::D2,
format: TextureFormat::Bgra8UnormSrgb,
mip_level_count: 1,
sample_count: 1,
usage: TextureUsages::TEXTURE_BINDING
| TextureUsages::COPY_DST
| TextureUsages::RENDER_ATTACHMENT,
},
..default()
};
// fill image.data with zeroes
image.resize(size);
let image_handle = images.add(image);
// Main Camera
commands
.spawn_bundle(Camera2dBundle {
camera: Camera {
priority: -1,
target: RenderTarget::Image(image_handle.clone()),
..default()
},
..default()
})
// UI is assumed to be done on the "full sized primary window", so Bevy can't yet meaningfully render it to
// a smaller image. This will be improved soon.
.insert(UiCameraConfig { show_ui: false });
commands
.spawn_bundle(Camera2dBundle {
camera_2d: Camera2d {
clear_color: ClearColorConfig::Custom(Color::rgb(0.1, 0.1, 0.1)),
..default()
},
..default()
})
.insert(RenderLayers::none());
commands.spawn_bundle(ImageBundle {
style: Style {
// Here, we have two options, by default, the second one is commented out.
// The first one only stretches the image up to the window size, this means
// that the image can (and will) be distorted if resized.
// The second does a slightly better but not perfect job with letterboxing.
// But I've tried to do UI stuff with the second approach and could not get it
// working, so, if you're doing UI and that sorta thing, you may need to use
// first approach.
size: Size::new(Val::Percent(100.0), Val::Percent(100.0)),
// size: Size::new(Val::Auto, Val::Auto),
// // Without this, the rendered image will overflow if it's smaller than it's initial size,
// // although, instead, it can squash vertically the image.
// max_size: Size::new(Val::Percent(100.0), Val::Percent(100.0)),
// margin: UiRect::all(Val::Auto),
..default()
},
image: image_handle.into(),
..default()
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment