开发者

what is source rectangle in spritebatch.draw in xna

开发者 https://www.devze.com 2023-02-14 14:16 出处:网络
What is the purpose of the source rectangle parameter in the SpriteBatch.Draw() method? 开发者_运维技巧MSDN says: A rectangle that specifies (in texels) the source texels from a texture. Use null to

What is the purpose of the source rectangle parameter in the SpriteBatch.Draw() method?

开发者_运维技巧

MSDN says: A rectangle that specifies (in texels) the source texels from a texture. Use null to draw the entire texture.

What does that mean?


The idea of the sourceRectangle is to allow you to implement what is both a performance optimisation and an artist convenience by arranging multiple sprites into a single texture. This is known as a "Texture Atlas" or a "Sprite Sheet".

what is source rectangle in spritebatch.draw in xna


(source: andrewrussell.net)

I explain why it is a performance optimisation in this answer. Basically it lets you reduce the number of texture-swaps. (So in the case of my illustration, if you're only drawing an animated character once, using a sprite-sheet will not improve performance.)

It also lets you implement tacky 2D special effects, like having a sprite "wipe" in:

what is source rectangle in spritebatch.draw in xna


(source: andrewrussell.net)

A texel is more-or-less the same thing as a pixel in the texture (a "texture pixel", if you will). So, when you draw your sprite, you specify the top-left corner of your sprite within the texture, along with its width and height. (The same as if you selected it in an image editor.)

If you pass in null for your source rectangle, XNA will assume a source rectangle that covers the entire texture.

The origin you specify to Draw is also measured in texels from the upper-left corner of the source rectangle.


In a situation where you have a single texture that contains different frames (animated textures), you will want to specify the source rectangle, so that you can draw a single frame from a texture.

i.e. Look at this spritesheet here


The source rectangle defines the area of the texture that will be displayed. So if you have a 40x40 texture, and your rectangle is (0, 0, 20, 20), only the top left corner of the texture will be displayed. If you specify null for the rectangle, you will draw the entire texture.

This can be helpful when drawing from a spritesheet (a collection of textures that are all put into one bigger texture), and also in image manipulation programs.

0

精彩评论

暂无评论...
验证码 换一张
取 消