Showing posts with label Image. Show all posts
Showing posts with label Image. Show all posts

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

Tuesday, 11 January 2011

Crop Texture2D in XNA

I needed to crop an image in XNA, but I didn't find a solution (Ok i really didn't search much :) ) and so I had to do it by myself. Here is the code in case you need it too. (XNA 4.0)

public static Texture2D Crop(Texture2D source, Rectangle area)
{
    if (source == null)
        return null;

    Texture2D cropped = new Texture2D(source.GraphicsDevice, area.Width, area.Height);
    Color[] data = new Color[source.Width * source.Height];
    Color[] cropData = new Color[cropped.Width * cropped.Height];

    source.GetData(data);

    int index = 0;
    for (int y = area.Y; y < area.Y + area.Height; y++)
    {
        for (int x = area.X; x < area.X + area.Width; x++)
        {
            cropData[index] = data[x + (y * source.Width)];
            index++;
        }
    }

    cropped.SetData(cropData);

    return cropped;
}