Friday 21 January 2011

How to flip Texture2D vertically or horizontally in XNA

Here is the code how you can flip a Texture2D image in XNA (4.0).

public static Texture2D Flip(Texture2D source, bool vertical, bool horizontal)
{
    Texture2D flipped = new Texture2D(source.GraphicsDevice, source.Width, source.Height);
    Color[] data = new Color[source.Width * source.Height];
    Color[] flippedData = new Color[data.Length];

    source.GetData(data);

    for (int x = 0; x < source.Width; x++)
        for (int y = 0; y < source.Height; y++)
        {
            int idx = (horizontal ? source.Width - 1 - x : x) +((vertical ? source.Height - 1 - y : y) * source.Width);
            flippedData[x + y * source.Width] = data[idx];
        }

        flipped.SetData(flippedData);

        return flipped;
}

1 comment:

  1. Excellent tutorial, just a few mistakes:

    "source.GetData"
    to
    "source.GetData"

    and well the ""

    But this is awesome, just used it and works like a charm :)

    Keep up the good work ( even if this is old :P )

    ReplyDelete