Taking screenshots in XNA
Wouldn’t it be nice if it was simple to add screenshot functionality to your games? People who play your games could easily post pictures online, gathering even more interest in and publicity for your game?
I’ve gathered some screenshot code I found on the web (credits in the code) in a little GraphicsDevice extension method. If you aren't familiar with extension methods, basically they add new functionality to existing classes - in this case adds two new methods to Microsoft's GraphicsDevice class.
The class is here C# (right click > "save as..."), or ZIP.
Complete codesample here.
To use it :
- add the GraphicsDeviceExtensions class to your project
- call the GraphicsDevice.PrepareScreenshot() before the spriteBatch.Begin()
- call the GraphicsDevice.SaveScreenshot() after spriteBatch.End()
If you pass the SaveScreenshot method a filename or path then that filename will be used. If you don’t then screendumps will be saved in a file called Screenshot_001.png, Screenshot_002.png, etc. in the running game’s folder.
In the code sample below, the screenshot is prepared on line 9 and the screenshot is taken on line 34.
bool doScreenshot = false; //set this to true to perform screenshot protected override void Draw(GameTime gameTime) { //if necessary, we prepare for a screenshot if (doScreenshot) { GraphicsDevice.PrepareScreenShot(); } //Clear graphicsdevice with blue background GraphicsDevice.Clear(Color.Orange); //begin drawing spriteBatch.Begin(); //write test string spriteBatch.DrawString(_defaultFont, "Screenshot test!", new Vector2(100, 100), Color.Red); //write whether we are running in HiDef or Reach graphics profile spriteBatch.DrawString(_defaultFont, "Profile: " + graphics.GraphicsProfile, new Vector2(100, 200), Color.DarkRed); //call superclass' Draw() base.Draw(gameTime); //end drawing spriteBatch.End(); //if necessary, we save the image to a screenshot if (doScreenshot) { GraphicsDevice.SaveScreenshot(); doScreenshot = false; } }
May 1st, 2013 at 16:39
This is a awsome class! But this is a bit weird, because you get automaticly a purple screen when you take a screenshot.
May 1st, 2013 at 18:13
Okay, that sounds like you're not calling GraphicsDevice.PrepareScreenShot _before_ SpriteBatch.Begin, and GraphicsDevice.SaveScreenShot _after_ SpriteBatch.End ....?
Have you tried downloading the codesample and comparing it with your code?
If you're still at a loss to the purple screen, send me the code for your Draw() method - my email is: "kr [at] rup [dot] dk" and I'll have a look at it
Kind regards - Jakob
August 25th, 2014 at 16:08
When i try to create 1++ screenshots its everytime the same shot even if the drawing has moved.
August 30th, 2014 at 13:11
Hi Kai
Would you mail me your code to look at?
Kind regards - Jakob