Ben*_*n S 5 .net c# xna image-manipulation
在我为XNA游戏制作的关卡编辑器(编辑器也在XNA中)我允许缩放Texture2D对象.
当用户试图保存关卡时,我想实际调整磁盘上的图像文件大小,这样就不需要在游戏中进行缩放.
有没有一种简单的方法可以从缩放的Texture2D对象创建图像文件(首选PNG)?
Lea*_*and 11
您可以通过渲染到所需大小的渲染目标来缩放纹理,然后保存渲染目标纹理.
这个简单的例子说明了如何做到这一点.忽略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);
}
}
Run Code Online (Sandbox Code Playgroud)