Most of developers use Bevy for game development, which usually involves lots of images.
To display an image, the image must be stored in the directory assets in the project root directory.
Assume we have an image named bevy_bird_dark.png in the directory assets.
We use the resource AssetServer to load images from the file system. The load method of AssetServer returns a Handle, which can be treated as a special type of pointers in Bevy. We pass the Handle into a SpriteBundle as its texture.
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()
});
}After the SpriteBundle is spawned, the image will be drawn on the screen as soon as it is ready, and will remain on the screen until it is despawned.
The origin of the camera of Camera2dBundle is at the center of the window. The default SpriteBundle will align the image centered at the origin. Thus the image is at the center of the window.
The full code is as follows:
use bevy::{
app::{App, Startup},
asset::AssetServer,
core_pipeline::core_2d::Camera2dBundle,
ecs::system::{Commands, Res},
sprite::SpriteBundle,
utils::default,
DefaultPlugins,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.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()
});
}Result:
➡️ Next: Obtaining Sizes Of Images
📘 Back: Table of contents
