[英]How to resize and save a Texture2D in XNA?
在我為 XNA 游戲制作的關卡編輯器中(編輯器也在 XNA 中),我允許縮放Texture2D對象。
當用戶嘗試保存關卡時,我想實際調整磁盤上的圖像文件大小,以便它不需要在游戲中縮放。
有沒有一種簡單的方法可以從縮放的 Texture2D object 創建圖像文件(首選 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);
}
}
我有這樣的代碼,可以制作更大/更小的紋理副本,但一段時間后出現錯誤。 在 30 次調整大小之后,我得到了異常,而不是第一次。
似乎是一個渲染目標問題,但我不確定。 想知道如果您也經常運行此代碼,您是否也會遇到這些異常?
你試過Texture2D.Save()嗎?
縮放圖像通常不會產生那么多開銷,另外,您不希望將相同紋理的不同大小加載到 memory 中,因為那會浪費。
當然,您可能正在編寫 Zune 游戲,這意味着我可能對那里的縮放不感興趣,但是,無論如何。
我認為您不能直接從 XNA 保存縮放后的圖像,但是,您可以使用 WinForms Image class 加載圖像,然后將其縮放到關卡編輯器中的尺寸並將其保存回磁盤。
如果您的紋理不是 BMP 或 PNG,您可能必須使用 Texture2D.Save() 命令將其轉換為可在圖像 class 中使用的格式。
該線程可能會幫助您使用圖像 class。 http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/6fe3d353-0b09-440b-95c9-701efdc9e20a/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.