Skip to content

Files

Latest commit

 

History

History
83 lines (63 loc) · 3.73 KB

obtaining_sizes_of_images.md

File metadata and controls

83 lines (63 loc) · 3.73 KB

Obtaining Sizes Of Images

In the previous tutorial, our app spawns a SpriteBundle and provides a Handle for the SpriteBundle's texture. We can access this Handle after it is spawned.

Since our Handle points to an Image, we will query &Handle<Image> in our system. The image data is stored in the resource Assets and can be accessed by Res<Assets<Image>>. We will use the &Handle<Image> to find the Image stored in Res<Assets<Image>>.

fn print_image_size(image_handles: Query<&Handle<Image>>, images: Res<Assets<Image>>) {
    let image_handle = image_handles.single();

    let Some(image) = images.get(image_handle) else {
        return;
    };

    println!("{}", image.size());
}

In this example, the app spawns exactly one Handle<Image>, so we can use single() of Query to access the Handle.

If the Image is ready to be drawn, images.get(image_handle) returns Some, otherwise it returns None.

After we obtained the Image as a variable, we can access its attributes, such as size(), width(), height(), aspect_ratio(), etc.

The full code is as follows:

use bevy::{
    app::{App, Startup, Update},
    asset::{AssetServer, Assets, Handle},
    core_pipeline::core_2d::Camera2dBundle,
    ecs::system::{Commands, Query, Res},
    render::texture::Image,
    sprite::SpriteBundle,
    utils::default,
    DefaultPlugins,
};

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(Update, print_image_size)
        .run();
}

fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.spawn(Camera2dBundle::default());

    commands.spawn(SpriteBundle {
        texture: asset_server.load("bevy_bird_dark.png"),
        ..default()
    });
}

fn print_image_size(image_handles: Query<&Handle<Image>>, images: Res<Assets<Image>>) {
    let image_handle = image_handles.single();

    let Some(image) = images.get(image_handle) else {
        return;
    };

    println!("{}", image.size());
}

Output:

[256, 256]
[256, 256]
[256, 256]
[256, 256]
[256, 256]
... (repeat infinitely)

➡️ Next: Resizing Images

📘 Back: Table of contents