1

i am trying to crop a texture2d in xna. i have found the following code which will crop the image on the top and right sides, i have played around with the code and cannot figure a way to crop all sides at a specific interval. below is the code i have been trying to modify:

any help or ideas would be much appreciated.

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);
4

1 回答 1

3

这是裁剪纹理的代码。请注意,该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的计算方式与第一个代码清单中的相同。)

于 2013-04-22T07:06:07.700 回答