XNA4.0 保存屏幕截图方法

方法取决于游戏配置里的开发模式

1.Reach模式:

  使用的是RenderTarget2D对象,将屏幕绘制至此对象,然后直接调用其保存命令即可。

  (RenderTarget2D也经常用于后期渲染)

RenderTarget2D screenshot;//添加绘制目标

protected override void LoadContent()
{
screenshot = new RenderTarget2D(GraphicsDevice, width, height, false, SurfaceFormat.Color, null);//初始化
}

protected override void UnloadContent()
{
screenshot.Dispose();//释放
}

int i = 0;//截图编号

protected override void Draw(GameTime)
{

GraphicsDevice.SetRenderTarget(screenshot); // 设置绘制目标
//
// 这里调用你的绘制(draw)命令绘制目标
//
GraphicsDevice.SetRenderTarget(null); // 解除设置

using(FileStream fs = new FileStream(@"screenshot"+(i++)+@".png", FileMode.OpenOrCreate))
{
screenshot.SaveAsPng(fs, width, height); // 将绘制目标保存为png
}


}

 

2.HiDef模式:

  比reach要简单不少。拷贝Buffer并保存即可。

public void ScreenShot(string prefix) { 
int w = GraphicsDevice.PresentationParameters.BackBufferWidth;
int h = GraphicsDevice.PresentationParameters.BackBufferHeight;

//强行调用一次Draw,用当前屏幕覆盖back buffer
Draw(new GameTime());

//拷贝backbuffer
int[] backBuffer = new int[w * h];
GraphicsDevice.GetBackBufferData(backBuffer);

//拷贝至texture
Texture2D texture = new Texture2D(GraphicsDevice, w, h, false, GraphicsDevice.PresentationParameters.BackBufferFormat);
texture.SetData(backBuffer);

//保存
Stream stream = File.OpenWrite(prefix + "_" + Guid.NewGuid().ToString() + ".png");
texture.SaveAsPng(stream, w, h);
stream.Close();


}

 

  

posted @ 2012-03-23 10:17  妖気  阅读(1144)  评论(0编辑  收藏  举报