Skip to content

Commit

Permalink
Sprite: allow using a sub-region (Rect) of the image (#6014)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
inodentry committed Sep 18, 2022
1 parent 43f9271 commit 53157c0
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 3 deletions.
3 changes: 1 addition & 2 deletions crates/bevy_sprite/src/render/mod.rs
Expand Up @@ -257,8 +257,7 @@ pub fn extract_sprites(
entity,
color: sprite.color,
transform: *transform,
// Use the full texture
rect: None,
rect: sprite.rect,
// Pass the custom size
custom_size: sprite.custom_size,
flip_x: sprite.flip_x,
Expand Down
5 changes: 4 additions & 1 deletion crates/bevy_sprite/src/sprite.rs
@@ -1,5 +1,5 @@
use bevy_ecs::component::Component;
use bevy_math::Vec2;
use bevy_math::{Rect, Vec2};
use bevy_reflect::Reflect;
use bevy_render::color::Color;

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

0 comments on commit 53157c0

Please sign in to comment.