Skip to content

Commit aa7b158

Browse files
Add a size method on Image. (#3696)
# Objective Add a simple way for user to get the size of a loaded texture in an Image object. Aims to solve #3689 ## Solution Add a `size() -> Vec2` method Add two simple tests for this method. Updates: . method named changed from `size_2d` to `size`
1 parent 142e7f3 commit aa7b158

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

crates/bevy_render/src/texture/image.rs

+39-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use crate::{
77
};
88
use bevy_asset::HandleUntyped;
99
use bevy_ecs::system::{lifetimeless::SRes, SystemParamItem};
10-
use bevy_math::Size;
10+
use bevy_math::{Size, Vec2};
1111
use bevy_reflect::TypeUuid;
1212
use thiserror::Error;
1313
use wgpu::{
@@ -118,6 +118,14 @@ impl Image {
118118
self.texture_descriptor.size.height as f32 / self.texture_descriptor.size.width as f32
119119
}
120120

121+
/// Returns the size of a 2D image.
122+
pub fn size(&self) -> Vec2 {
123+
Vec2::new(
124+
self.texture_descriptor.size.width as f32,
125+
self.texture_descriptor.size.height as f32,
126+
)
127+
}
128+
121129
/// Resizes the image to the new size, by removing information or appending 0 to the `data`.
122130
/// Does not properly resize the contents of the image, but only its internal `data` buffer.
123131
pub fn resize(&mut self, size: Extent3d) {
@@ -440,3 +448,33 @@ impl RenderAsset for Image {
440448
})
441449
}
442450
}
451+
452+
#[cfg(test)]
453+
mod test {
454+
455+
use super::*;
456+
457+
#[test]
458+
fn image_size() {
459+
let size = Extent3d {
460+
width: 200,
461+
height: 100,
462+
depth_or_array_layers: 1,
463+
};
464+
let image = Image::new_fill(
465+
size,
466+
TextureDimension::D2,
467+
&[0, 0, 0, 255],
468+
TextureFormat::Rgba8Unorm,
469+
);
470+
assert_eq!(
471+
Vec2::new(size.width as f32, size.height as f32),
472+
image.size()
473+
);
474+
}
475+
#[test]
476+
fn image_default_size() {
477+
let image = Image::default();
478+
assert_eq!(Vec2::new(1.0, 1.0), image.size());
479+
}
480+
}

0 commit comments

Comments
 (0)