我想写一些生成JPG图像的单元测试。我正在使用XNA进行游戏,想要进行一些渲染测试,我可以运行并直观地检查我没有破坏任何东西等。
我有一个单元测试项目调用我的代码来生成像三角形条带这样的XNA对象,但所有渲染示例似乎都假设我有一个Game对象并且渲染到关联的GraphicsDevice,这是一个屏幕上的窗口。
如果可能的话,我想在内存中渲染并保存我可以在测试完成后检查的JPG图像。或者,我想我可以在单元测试中实例化一个Game对象,渲染到屏幕然后转储到JPG,如下所述:How to make screenshot using C# & XNA?
但这听起来效率不高。
所以简单地说,有没有办法在XNA Game之外实例化一个写入内存缓冲区的GraphicsDevice对象?
答案 0 :(得分:0)
我最终从System.Windows.Forms实例化一个Control对象。我做了我的单元测试项目的这部分,所以我的游戏不依赖于Windows Forms。
这是我用来为我的测试提供生成JPG的功能的类:
public class JPGGraphicsDeviceProvider
{
private Control _c;
private RenderTarget2D _renderTarget;
private int _width;
private int _height;
public JPGGraphicsDeviceProvider(int width, int height)
{
_width = width;
_height = height;
_c = new Control();
PresentationParameters parameters = new PresentationParameters()
{
BackBufferWidth = width,
BackBufferHeight = height,
BackBufferFormat = SurfaceFormat.Color,
DepthStencilFormat = DepthFormat.Depth24,
DeviceWindowHandle = _c.Handle,
PresentationInterval = PresentInterval.Immediate,
IsFullScreen = false,
};
GraphicsDevice = new GraphicsDevice(GraphicsAdapter.DefaultAdapter,
GraphicsProfile.Reach,
parameters);
// Got this idea from here: http://xboxforums.create.msdn.com/forums/t/67895.aspx
_renderTarget = new RenderTarget2D(GraphicsDevice,
GraphicsDevice.PresentationParameters.BackBufferWidth,
GraphicsDevice.PresentationParameters.BackBufferHeight);
GraphicsDevice.SetRenderTarget(_renderTarget);
}
/// <summary>
/// Gets the current graphics device.
/// </summary>
public GraphicsDevice GraphicsDevice { get; private set; }
public void SaveCurrentImage(string jpgFilename)
{
GraphicsDevice.SetRenderTarget(null);
int w = GraphicsDevice.PresentationParameters.BackBufferWidth;
int h = GraphicsDevice.PresentationParameters.BackBufferHeight;
using (Stream stream = new FileStream(jpgFilename, FileMode.Create))
{
_renderTarget.SaveAsJpeg(stream, w, h);
}
GraphicsDevice.SetRenderTarget(_renderTarget);
}
}
然后在我的测试中,我只是实例化它并使用提供的GraphicsDevice:
[TestClass]
public class RenderTests
{
private JPGGraphicsDeviceProvider _jpgDevice;
private RenderPanel _renderPanel;
public RenderTests()
{
_jpgDevice = new JPGGraphicsDeviceProvider(512, 360);
_renderPanel = new RenderPanel(_jpgDevice.GraphicsDevice);
}
[TestMethod]
public void InstantiatePrism6()
{
ColorPrism p = new ColorPrism(6, Color.RoyalBlue, Color.Pink);
_renderPanel.Add(p);
_renderPanel.Draw();
_jpgDevice.SaveCurrentImage("six-Prism.jpg");
}
}
我确定它不是没有错误的,但它现在似乎有效。