Skip to content

Commit 53157c0

Browse files
committed
Sprite: allow using a sub-region (Rect) of the image (#6014)
Very small change that improves the usability of `Sprite`. Before this PR, the only way to render a portion of an `Image` was to create a `TextureAtlas` and use `TextureAtlasSprite`/`SpriteSheetBundle`. This can be very annoying for one-off use cases, like if you just want to remove a border from an image, or something. Using `Sprite`/`SpriteBundle` always meant that the entire full image would be rendered. This PR adds an optional `rect` field to `Sprite`, allowing a sub-rectangle of the image to be rendered. This is similar to how texture atlases work, but does not require creating a texture atlas asset, making it much more convenient and efficient for quick one-off use cases. Given how trivial this change is, it really felt like missing functionality in Bevy's sprites API. ;) ## Changelog Added: - `rect` field on `Sprite`: allows rendering a portion of the sprite's image; more convenient for one-off use cases, than creating a texture atlas.
1 parent 43f9271 commit 53157c0

File tree

2 files changed

+5
-3
lines changed

2 files changed

+5
-3
lines changed

crates/bevy_sprite/src/render/mod.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -257,8 +257,7 @@ pub fn extract_sprites(
257257
entity,
258258
color: sprite.color,
259259
transform: *transform,
260-
// Use the full texture
261-
rect: None,
260+
rect: sprite.rect,
262261
// Pass the custom size
263262
custom_size: sprite.custom_size,
264263
flip_x: sprite.flip_x,

crates/bevy_sprite/src/sprite.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use bevy_ecs::component::Component;
2-
use bevy_math::Vec2;
2+
use bevy_math::{Rect, Vec2};
33
use bevy_reflect::Reflect;
44
use bevy_render::color::Color;
55

@@ -15,6 +15,9 @@ pub struct Sprite {
1515
/// An optional custom size for the sprite that will be used when rendering, instead of the size
1616
/// of the sprite's image
1717
pub custom_size: Option<Vec2>,
18+
/// An optional rectangle representing the region of the sprite's image to render, instead of
19+
/// rendering the full image. This is an easy one-off alternative to using a texture atlas.
20+
pub rect: Option<Rect>,
1821
/// [`Anchor`] point of the sprite in the world
1922
pub anchor: Anchor,
2023
}

0 commit comments

Comments
 (0)