如何在XNA中调整和保存Texture2D?

在我为XNA游戏制作的关卡编辑器(编辑器也在XNA中)我允许缩放Texture2D对象。

当用户试图保存关卡时,我想实际调整磁盘上的图像文件大小,这样就不需要在游戏中进行缩放。

有没有一种简单的方法可以从缩放的Texture2D对象创建图像文件(首选PNG)?

您可以通过渲染到所需大小的渲染目标来缩放纹理,然后保存渲染目标纹理。

这个简单的例子说明了如何做到这一点。 忽略GraphicsDevice的设置,这只是为了制作一个小的自包含示例。 有趣的是创建渲染目标并绘制缩放纹理。 您应该尽可能地重用渲染目标(所有相同大小的图像都可以重用渲染目标)。

using System; using System.Runtime.InteropServices; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; class Program { [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetConsoleWindow(); static void Main(string[] args) { string sourceImagePath = args[0]; string destinationImagePath = args[1]; int desiredWidth = int.Parse(args[2]); int desiredHeight = int.Parse(args[3]); GraphicsDevice graphicsDevice = new GraphicsDevice( GraphicsAdapter.DefaultAdapter, DeviceType.Hardware, GetConsoleWindow(), new PresentationParameters()); SpriteBatch batch = new SpriteBatch(graphicsDevice); Texture2D sourceImage = Texture2D.FromFile( graphicsDevice, sourceImagePath); RenderTarget2D renderTarget = new RenderTarget2D( graphicsDevice, desiredWidth, desiredHeight, 1, SurfaceFormat.Color); Rectangle destinationRectangle = new Rectangle( 0, 0, desiredWidth, desiredHeight); graphicsDevice.SetRenderTarget(0, renderTarget); batch.Begin(); batch.Draw(sourceImage, destinationRectangle, Color.White); batch.End(); graphicsDevice.SetRenderTarget(0, null); Texture2D scaledImage = renderTarget.GetTexture(); scaledImage.Save(destinationImagePath, ImageFileFormat.Png); } } 

你试过Texture2D.Save()吗?

缩放图像通常不会产生太大的开销,而且,您不希望将相同纹理的不同大小加载到内存中,因为这会浪费。

当然,你可能正在写一个Zune游戏,这意味着我可能不在那里扩展,但是,无论如何。

我不认为您可以直接从XNA保存缩放图像,但是,您可以使用WinForms Image类加载图像,然后将其缩放到关卡编辑器中的维度并将其保存回磁盘。

如果您的纹理不是BMP或PNG,则可能必须使用Texture2D.Save()命令将其转换为可在Image类中使用的格式。

此线程可能会帮助您使用Image类。 http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/6fe3d353-0b09-440b-95c9-701efdc9e20a/

我有这样的代码,它可以制作一个更大/更小的纹理副本但是我会在一段时间后得到错误。 30次resize后,我得到了例外,而不是第一次。

似乎是一个rendertarget问题,但我不确定。 如果您经常运行此代码,也不知道是否也会遇到这些exception?