diff --git a/crates/bevy_image/src/texture_atlas.rs b/crates/bevy_image/src/texture_atlas.rs index 36e2acd864..1e9873d048 100644 --- a/crates/bevy_image/src/texture_atlas.rs +++ b/crates/bevy_image/src/texture_atlas.rs @@ -1,6 +1,6 @@ use bevy_app::prelude::*; use bevy_asset::{Asset, AssetApp as _, AssetId, Assets, Handle}; -use bevy_math::{URect, UVec2}; +use bevy_math::{Rect, URect, UVec2}; use bevy_platform_support::collections::HashMap; #[cfg(feature = "bevy_reflect")] use bevy_reflect::{std_traits::ReflectDefault, Reflect}; @@ -51,7 +51,7 @@ impl TextureAtlasSources { }) } - /// Retrieves the texture *section* rectangle of the given `texture` handle. + /// Retrieves the texture *section* rectangle of the given `texture` handle in pixels. pub fn texture_rect( &self, layout: &TextureAtlasLayout, @@ -59,6 +59,20 @@ impl TextureAtlasSources { ) -> Option { layout.textures.get(self.texture_index(texture)?).cloned() } + + /// Retrieves the texture *section* rectangle of the given `texture` handle in UV coordinates. + /// These are within the range [0..1], as a fraction of the entire texture atlas' size. + pub fn uv_rect( + &self, + layout: &TextureAtlasLayout, + texture: impl Into>, + ) -> Option { + self.texture_rect(layout, texture).map(|rect| { + let rect = rect.as_rect(); + let size = layout.size.as_vec2(); + Rect::from_corners(rect.min / size, rect.max / size) + }) + } } /// Stores a map used to lookup the position of a texture in a [`TextureAtlas`].