Reputation: 16081
I have a set of images in which each image needs to be able to rotate to 90 degrees, 180 degrees, and 270 degrees. All of these images are of type Texture2D. Are there built in functions to accomplish this for me? Or should I load additional rotated images of each image? Or is there a better way of completing this task?
Upvotes: 1
Views: 6957
Reputation: 1
If you want to rotate only Texture2D field without changing anything in the Draw method, You can use this (it rotates input 90 degrees clockwise):
public static Texture2D RotateTexture90Deegrees(Texture2D input)
{
Texture2D rotated = null;
if (input != null)
{
rotated = new Texture2D(input.GraphicsDevice, input.Width, input.Height);
Color[] data = new Color[input.Width * input.Height];
Color[] rotated_data = new Color[data.Length];
input.GetData<Color>(data);
var Xcounter = 1;
var Ycounter = 0;
for (int i = 0; i < data.Length; i++)
{
rotated_data[i] = data[((input.Width * Xcounter)-1) - Ycounter];
Xcounter += 1;
if (Xcounter > input.Width)
{
Xcounter = 1;
Ycounter += 1;
}
}
rotated.SetData<Color>(rotated_data);
}
return rotated;
}
Upvotes: 0
Reputation: 7198
You can rotate (and scale) your Textures as you draw them to the buffer using SpriteBatch.Draw
, although you will need to specify most (or all) of the arguments. Angles are given in radians.
SpriteBatch.Begin();
angle = (float)Math.PI / 2.0f; // 90 degrees
scale = 1.0f;
SpriteBatch.Draw(myTexture, sourceRect, destRect, Color.White, angle,
position, scale, SpriteEffects.None, 0.0f);
SpriteBatch.End();
http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.draw.aspx
You could also load pre-rotated copies of the images, but you'll probably get the usual Premature Optimization lecture.
Upvotes: 5