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

No comments:

Post a Comment