在xna c#中裁剪纹理2d
本文关键字:纹理 2d 裁剪 xna | 更新日期: 2023-09-27 18:10:19
我正在尝试在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);
下面是裁剪纹理的代码。请注意,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
的计算方法与第一个代码清单相同)