letterbox/
letterbox.rs

1use macroquad::prelude::*;
2
3const VIRTUAL_WIDTH: f32 = 1280.0;
4const VIRTUAL_HEIGHT: f32 = 720.0;
5
6#[macroquad::main("Letterbox")]
7async fn main() {
8    // Setup 'render_target', used to hold the rendering result so we can resize it
9    let render_target = render_target(VIRTUAL_WIDTH as u32, VIRTUAL_HEIGHT as u32);
10    render_target.texture.set_filter(FilterMode::Linear);
11
12    // Setup camera for the virtual screen, that will render to 'render_target'
13    let mut render_target_cam =
14        Camera2D::from_display_rect(Rect::new(0., 0., VIRTUAL_WIDTH, VIRTUAL_HEIGHT));
15    render_target_cam.render_target = Some(render_target.clone());
16
17    loop {
18        // Get required scaling value
19        let scale: f32 = f32::min(
20            screen_width() / VIRTUAL_WIDTH,
21            screen_height() / VIRTUAL_HEIGHT,
22        );
23
24        // Mouse position in the virtual screen
25        let virtual_mouse_pos = Vec2 {
26            x: (mouse_position().0 - (screen_width() - (VIRTUAL_WIDTH * scale)) * 0.5) / scale,
27            y: (mouse_position().1 - (screen_height() - (VIRTUAL_HEIGHT * scale)) * 0.5) / scale,
28        };
29
30        // ------------------------------------------------------------------------
31        // Begin drawing the virtual screen to 'render_target'
32        // ------------------------------------------------------------------------
33        set_camera(&render_target_cam);
34
35        clear_background(LIGHTGRAY);
36
37        draw_text("Hello Letterbox", 20.0, 20.0, 30.0, DARKGRAY);
38        draw_circle(VIRTUAL_WIDTH / 2.0 - 65.0, VIRTUAL_HEIGHT / 2.0, 35.0, RED);
39        draw_circle(VIRTUAL_WIDTH / 2.0 + 65.0, VIRTUAL_HEIGHT / 2.0, 35.0, BLUE);
40        draw_circle(
41            VIRTUAL_WIDTH / 2.0,
42            VIRTUAL_HEIGHT / 2.0 - 65.0,
43            35.0,
44            YELLOW,
45        );
46
47        draw_circle(virtual_mouse_pos.x, virtual_mouse_pos.y, 15.0, BLACK);
48
49        // ------------------------------------------------------------------------
50        // Begin drawing the window screen
51        // ------------------------------------------------------------------------
52        set_default_camera();
53
54        clear_background(BLACK); // Will be the letterbox color
55
56        // Draw 'render_target' to window screen, porperly scaled and letterboxed
57        draw_texture_ex(
58            &render_target.texture,
59            (screen_width() - (VIRTUAL_WIDTH * scale)) * 0.5,
60            (screen_height() - (VIRTUAL_HEIGHT * scale)) * 0.5,
61            WHITE,
62            DrawTextureParams {
63                dest_size: Some(vec2(VIRTUAL_WIDTH * scale, VIRTUAL_HEIGHT * scale)),
64                flip_y: true, // Must flip y otherwise 'render_target' will be upside down
65                ..Default::default()
66            },
67        );
68
69        next_frame().await;
70    }
71}