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.
This commit is contained in:
Ida Iyes 2022-09-18 22:49:27 +00:00
parent 43f9271d13
commit 53157c0801
2 changed files with 5 additions and 3 deletions

View file

@ -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,

View file

@ -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;
@ -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,
}