在xna c#中的四周裁剪texture2d

时间:2013-04-21 23:57:27

标签: c# xna crop texture2d

我正在尝试在xna中裁剪texture2d。我发现下面的代码将在顶部和右侧裁剪图像,我已经玩了代码,无法想办法以特定的间隔裁剪所有边。下面是我一直试图修改的代码:

任何帮助或想法将不胜感激。

Rectangle area = new Rectangle(0, 0, 580, 480);

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

        heightMap1.GetData(data);

        int index = 0;


        for (int y = 0; y < area.Y + area.Height; y++) // for each row
        {

                for (int x = 0; x < area.X + area.Width; x++) // for each column 
                {
                    cropData[index] = data[x + (y * heightMap1.Width)];
                    index++;
                }

        }

    cropped.SetData(cropData);

1 个答案:

答案 0 :(得分:2)

以下是裁剪纹理的代码。请注意,GetData方法已经可以选择图像的矩形子部分 - 无需手动裁剪。

// Get your texture
Texture2D texture = Content.Load<Texture2D>("myTexture");

// Calculate the cropped boundary
Rectangle newBounds = texture.Bounds;
const int resizeBy = 20;
newBounds.X += resizeBy;
newBounds.Y += resizeBy;
newBounds.Width -= resizeBy * 2;
newBounds.Height -= resizeBy * 2;

// Create a new texture of the desired size
Texture2D croppedTexture = new Texture2D(GraphicsDevice, newBounds.Width, newBounds.Height);

// Copy the data from the cropped region into a buffer, then into the new texture
Color[] data = new Color[newBounds.Width * newBounds.Height];
texture.GetData(0, newBounds, data, 0, newBounds.Width * newBounds.Height);
croppedTexture.SetData(data);

当然,请记住SpriteBatch.Draw可以使用sourceRectangle参数,因此您甚至可能根本不需要复制纹理数据!只需使用原始纹理的子部分。例如:

spriteBatch.Draw(texture, Vector2.Zero, newBounds, Color.White);

(其中newBounds的计算方法与第一个代码清单相同。)