Saturday, November 17, 2007

How do I scale the size of a sprite?

Question: How do I scale the size of a sprite?

Answer: Scaling the size of a sprite when drawn consists of only one step: modifying the scale parameter of a spriteBatch.Draw call.

After creating a SpriteBatch, between the Begin and End calls, you will want to call spriteBatch.Draw(...); There are seven different overloads of Draw but only two of them take scale parameters. These are overloads 6 and 7.

You would call the Draw method with overload 6 as follows:

spriteBatch.Draw(texture, position, sourceRect, color, rotation,
origin, scale, spriteEffects, depth);

The seventh parameter is the scale. This parameter is a float. The default value is 1. Note that if you specify 0, the sprite will dissapear because all its dimensions will be multiplied by 0 which will result in 0.

You would call the Draw method with overload 7 as follows:

spriteBatch.Draw(texture, position, sourceRect, color, rotation, origin, scaleVector, spriteEffects, depth);

Again, the seventh parameter is the scale parameter. This parameter is different from overload 6 in that it is a Vector2 instead of a float. The reason for this is so that the user can scale the width of the texture differently from the height.

Note: You could also scale a texture by using the destination rectangle, but that will not be covered in this post.

No comments: