Load The Texture
The first part of loading sprites into Amethyst is to read the image into memory.
The following snippet shows how to load a PNG / JPEG / GIF / ICO image:
extern crate amethyst;
use amethyst::assets::{AssetStorage, Handle, Loader};
use amethyst::prelude::*;
use amethyst::renderer::{formats::texture::ImageFormat, Texture};
pub fn load_texture<N>(name: N, world: &World) -> Handle<Texture>
where
N: Into<String>,
{
let loader = world.read_resource::<Loader>();
loader.load(
name,
ImageFormat::default(),
(),
&world.read_resource::<AssetStorage<Texture>>(),
)
}
#[derive(Debug)]
struct ExampleState;
impl SimpleState for ExampleState {
fn on_start(&mut self, data: StateData<'_, GameData<'_, '_>>) {
let texture_handle = load_texture("texture/sprite_sheet.png", &data.world);
}
}
fn main() {}
There is one thing that may surprise you.
-
You don't get back the
Texture
, but aHandle<Texture>
, which is a cloneable reference to the texture.When you use
loader.load(..)
to load anAsset
, the method returns immediately with a unique handle for your texture. The actual asset loading is handled asynchronously, so if you attempt to use the texture handle to retrieve the texture, such as withworld.read_resource::<AssetStorage<Texture>>()
.get(texture_handle)
, you will get aNone
until theTexture
has finished loading.
The loaded texture will use nearest filtering, i.e. the pixels won't be interpolated.
If you want to tweak the sampling, you can change ImageFormat::default()
to
ImageFormat(my_config)
, and create your own my_config
like this:
extern crate amethyst;
use amethyst::renderer::rendy::hal::image::{Filter, SamplerInfo, WrapMode};
use amethyst::renderer::rendy::texture::image::{ImageTextureConfig, Repr, TextureKind};
let my_config = ImageTextureConfig {
// Determine format automatically
format: None,
// Color channel
repr: Repr::Srgb,
// Two-dimensional texture
kind: TextureKind::D2,
sampler_info: SamplerInfo::new(Filter::Linear, WrapMode::Clamp),
// Don't generate mipmaps for this image
generate_mips: false,
premultiply_alpha: true,
};