Michael
Michael

Reputation: 922

Get width and height from an image in Bevy

I am fairly new to Bevy and rust. I want to load an png image and get the width and height of it. The code below does not print "found resource ...".

fn setup( mut commands: Commands,
      asset_server: Res<AssetServer>,
      mut materials: ResMut<Assets<Image>>) {
let texture_handle = asset_server.load("board.png");

//materials.add(texture_handle.clone().into()); //Gives error: the trait `From<Handle<_>>` is not implemented for `bevy::prelude::Image`

commands.spawn().insert_bundle(SpriteBundle {
    texture: texture_handle.clone(),
    ..Default::default()
}).insert(BackgroundSprite);

if let Some(image) = materials.get(texture_handle) {
    print!("found resource with width and height: [{},{}]", image.texture_descriptor.size.width, image.texture_descriptor.size.height);
}

}

Upvotes: 5

Views: 3401

Answers (1)

Michael
Michael

Reputation: 922

I figured it out after some help on the Bevy Discord help channle.

Resources are loaded asynchronously and has to be accessed at a later point. See AssetEvent example here

I am a beginner when it comes to Rust so I wont say this is the way to do it. But here is my result:

#[derive(Component)]
pub struct BackgroundHandle {
    handle: Handle<Image>,
}

#[derive(Component)]
pub struct BackgroundSpriteSize {
    width: u32,
    height: u32,
}

fn setup( mut commands: Commands,
            mut app_state: ResMut<State<BoardState>>,
            asset_server: Res<AssetServer>) {
    let texture_handle = asset_server.load("board.png");

    commands.spawn().insert_bundle(SpriteBundle {
        texture: texture_handle.clone(),
        ..Default::default()
    }).insert(BackgroundSpriteBundle);

    commands.insert_resource(BackgroundHandle {
        handle: texture_handle,
    });

    app_state.set(BoardState::Initializing);
}

fn setupBounds(mut commands: Commands,
                mut app_state: ResMut<State<BoardState>>,
                mut ev_asset: EventReader<AssetEvent<Image>>,
                assets: Res<Assets<Image>>,
                bg: Res<BackgroundHandle>) {

    for ev in ev_asset.iter() {
        match ev {
            AssetEvent::Created { handle } => {
                if *handle == bg.handle {
                    let img = assets.get(bg.handle.clone()).unwrap();

                    let bg_size = BackgroundSpriteSize {
                        width: img.texture_descriptor.size.width,
                        height: img.texture_descriptor.size.height,
                    };

                    commands.insert_resource(bg_size);
                    app_state.set(BoardState::Initialized);
                }
            },
            _ => {

            }
        }
    }
}

Upvotes: 2

Related Questions