Skip to content

Commit

Permalink
Add a size method on Image. (bevyengine#3696)
Browse files Browse the repository at this point in the history
# Objective

Add a simple way for user to get the size of a loaded texture in an Image object.
Aims to solve bevyengine#3689

## Solution

Add a `size() -> Vec2` method
Add two simple tests for this method.

Updates:
. method named changed from `size_2d` to `size`
  • Loading branch information
BorisBoutillier committed Feb 4, 2022
1 parent 142e7f3 commit aa7b158
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion crates/bevy_render/src/texture/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{
};
use bevy_asset::HandleUntyped;
use bevy_ecs::system::{lifetimeless::SRes, SystemParamItem};
use bevy_math::Size;
use bevy_math::{Size, Vec2};
use bevy_reflect::TypeUuid;
use thiserror::Error;
use wgpu::{
Expand Down Expand Up @@ -118,6 +118,14 @@ impl Image {
self.texture_descriptor.size.height as f32 / self.texture_descriptor.size.width as f32
}

/// Returns the size of a 2D image.
pub fn size(&self) -> Vec2 {
Vec2::new(
self.texture_descriptor.size.width as f32,
self.texture_descriptor.size.height as f32,
)
}

/// Resizes the image to the new size, by removing information or appending 0 to the `data`.
/// Does not properly resize the contents of the image, but only its internal `data` buffer.
pub fn resize(&mut self, size: Extent3d) {
Expand Down Expand Up @@ -440,3 +448,33 @@ impl RenderAsset for Image {
})
}
}

#[cfg(test)]
mod test {

use super::*;

#[test]
fn image_size() {
let size = Extent3d {
width: 200,
height: 100,
depth_or_array_layers: 1,
};
let image = Image::new_fill(
size,
TextureDimension::D2,
&[0, 0, 0, 255],
TextureFormat::Rgba8Unorm,
);
assert_eq!(
Vec2::new(size.width as f32, size.height as f32),
image.size()
);
}
#[test]
fn image_default_size() {
let image = Image::default();
assert_eq!(Vec2::new(1.0, 1.0), image.size());
}
}

0 comments on commit aa7b158

Please sign in to comment.