Create Texture from bytes #2846
-
I'm sorry if this is explained in an example or if it was asked before, I couldn't find it anywhere. I am generating a texture represented as an array of rgba bytes. How do I render that as a 2d sprite with bevy? I am setting up a startup system like the following. fn setup_sprite_thing(
mut commands: Commands,
mut textures: ResMut<Assets<Texture>>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
use bevy::render::texture::{Extent3d, TextureDimension, TextureFormat};
let (width, height) = (256, 256);
let mut bytes = Vec::with_capacity(width * height * 4);
for _y in 0..height {
for _x in 0..width {
bytes.push(0xff);
bytes.push(0x00);
bytes.push(0x00);
bytes.push(0xff);
}
}
let texture = Texture::new(
Extent3d::new(width as u32, height as u32, 1),
TextureDimension::D2,
bytes,
TextureFormat::Rgba8Uint,
);
let texture_handle = textures.add(texture);
commands.spawn_bundle(OrthographicCameraBundle::new_2d());
commands.spawn_bundle(SpriteBundle {
material: materials.add(texture_handle.into()),
..Default::default()
});
} Nothing except the usual grey background is showing up on the window. Is there any step I'm missing, or something I'm doing wrong? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
The code is correct but you need to use the |
Beta Was this translation helpful? Give feedback.
-
seems like |
Beta Was this translation helpful? Give feedback.
-
I'm getting errors on these lines: commands.spawn_bundle(SpriteBundle {
material: materials.add(texture_handle.into()),
..Default::default()
}); I replaced them with this (and changed the function signature) and it seemed to do the correct thing: fn my_func(
...
mut images: ResMut<Assets<Image>>,
...
) {
let image = Image::new(
Extent3d {
width,
height,
depth_or_array_layers: 1,
},
TextureDimension::D2,
bytes,
TextureFormat::Rgba8Uint,
RenderAssetUsages::MAIN_WORLD | RenderAssetUsages::RENDER_WORLD,
);
commands.spawn(SpriteBundle {
texture: images.add(image),
..Default::default()
}); |
Beta Was this translation helpful? Give feedback.
The code is correct but you need to use the
TextureFormat::Rgba8Unorm
format, then it works and displays a red square.