Trying to Take a Snapshot of Only a Portion of the Screen In-Game
I'm working on a snapshot mechanic for a 2D project, and I want to have a second, smaller camera that lays over the top of the main camera to take the photos. I've already got my snapshot camera functioning the way I want except for one thing. When I take photos with the camera, it renders the correct area and with the correct resolution, but it puts it on a texture that includes the entire rest of the (empty) screen, so there ends up being a lot of negative space around the desired image.
I think it has something to do with ReadPixels(), but I can't figure out how to fix it.
Here are some examples of how they turn out (featuring photos saved on my computer that I used for testing purposes):
And my code:
private void OnPostRender()
{
if (takeScreenshot)
{
takeScreenshot = false;
RenderTexture rt = myCamera.targetTexture;
//create a Texture2D to store data from the targetTexture
Texture2D renderResult = new Texture2D(rt.width, rt.height, TextureFormat.RGBA32, false);
Rect rect = new Rect(0, 0, rt.width, rt.height);
renderResult.ReadPixels(rect, 0, 0);
//encode the render result into a PNG and save it
byte[] byteArray = renderResult.EncodeToPNG();
System.IO.File.WriteAllBytes(Application.dataPath + "/CameraScreenshot_" + System.DateTime.Now.ToString("yyMMddhhmmss") + ".png", byteArray);
print("Saved screenshot at " + Application.dataPath);
//release rt and change targetTexture back to null
RenderTexture.ReleaseTemporary(rt);
myCamera.targetTexture = null;
}
}
private void TakeScreenshot(int w, int h)
{
myCamera.targetTexture = RenderTexture.GetTemporary(w, h, 16);
RenderTexture.active = myCamera.targetTexture;
takeScreenshot = true;
}
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
TakeScreenshot(myCamera.pixelWidth, myCamera.pixelHeight);
}
}
Your answer
Follow this Question
Related Questions
Rendering Camera to PNG produces completely grey image. 1 Answer
Get Colors from RenderTexture faster! 1 Answer
RenderTexture to Texture2D very slowly 0 Answers
Wrong Coloring (Sometimes) when capturing "Screen"-shot 1 Answer
How to sync RenderTextures so that they all render once per frame 0 Answers