Skip to content

Instantly share code, notes, and snippets.

@profexorgeek
Last active November 16, 2018 14:09
Show Gist options
  • Save profexorgeek/8578408ad4c58a1fad4c0ef7e2fee2ea to your computer and use it in GitHub Desktop.
Save profexorgeek/8578408ad4c58a1fad4c0ef7e2fee2ea to your computer and use it in GitHub Desktop.
This is a raw paste of the screenshot utility I use for debugging purposes in Masteroid. This demonstrates how to render to a buffer (render target) and save that buffer as a png in the FlatRedBall game engine.
using FlatRedBall;
using FlatRedBall.Graphics;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.IO;
using System.Text.RegularExpressions;
namespace Masteroid.Utilities
{
public class ScreenshotUtility
{
private static ScreenshotUtility instance;
public static ScreenshotUtility Instance
{
get
{
if (instance == null)
{
instance = new ScreenshotUtility();
}
return instance;
}
}
public string SavePath { get; set; }
private ScreenshotUtility()
{
SavePath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
}
public void SaveScreenshotPng(Camera camera = null)
{
if (!FlatRedBallServices.IsInitialized)
{
throw new Exception("FlatRedBall must be fully initialized before you can take a screenshot!");
}
camera = camera ?? Camera.Main;
var gfx = FlatRedBallServices.GraphicsDevice;
var width = FlatRedBallServices.GraphicsOptions.ResolutionWidth;
var height = FlatRedBallServices.GraphicsOptions.ResolutionHeight;
var buffer = new RenderTarget2D(
FlatRedBallServices.GraphicsDevice,
width,
height);
// get existing render target
var existingTargets = gfx.GetRenderTargets();
// render
gfx.SetRenderTarget(buffer);
Renderer.DrawCamera(camera, null);
// restore render targets
gfx.SetRenderTargets(existingTargets);
var path = Path.Combine(SavePath, GetFilename());
if (File.Exists(path))
{
throw new Exception($"Existing pathname generated: {path}");
}
using (Stream stream = System.IO.File.Create(path))
{
buffer.SaveAsPng(stream, width, height);
}
}
private string GetFilename()
{
var timestamp = Regex.Replace(DateTime.Now.ToString("G"), "[^0-9]", "_");
return $"masteroid_{timestamp}.png";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment