gpt4 book ai didi

bevy - 从 Bevy 中获取图像的宽度和高度

转载 作者:行者123 更新时间:2023-12-05 05:49:30 25 4
gpt4 key购买 nike

我对 Bevy 和 Rust 还很陌生。我想加载一个 png 图像并获取它的宽度和高度。下面的代码不会打印“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);
}

最佳答案

在 Bevy Discord 帮助 channel 的一些帮助之后我弄明白了。

资源是异步加载的,必须在稍后访问。参见 AssetEvent example here

我是 Rust 的初学者,所以我不会说这是实现它的方法。但这是我的结果:

#[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);
}
},
_ => {

}
}
}
}

关于bevy - 从 Bevy 中获取图像的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70657798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com