将ScreenshotHandler.cs挂载到某个相机,需要截图时调用TakeScreenshot_static即可。
ScreenshotHandler.TakeScreenshot_static(600,1080);
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScreenshotHandler : MonoBehaviour {
private static ScreenshotHandler instance;
private Camera myCamera;
private bool takeScreenshotOnNextFrame;
private void Awake()
{
instance = this;
myCamera = GetComponent();
}
private void OnPostRender()
{
if(takeScreenshotOnNextFrame)
{
takeScreenshotOnNextFrame = false;
RenderTexture renderTexture = myCamera.targetTexture;
Texture2D renderResult = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.ARGB32, false);
Rect rect = new Rect(0, 0, renderTexture.width, renderTexture.height);
renderResult.ReadPixels(rect, 0, 0);
byte[] byteArray = renderResult.EncodeToPNG();
string file = Application.dataPath + "/CameraScreenShot.png";
Debug.Log(file);
System.IO.File.WriteAllBytes(file, byteArray);
RenderTexture.ReleaseTemporary(renderTexture);
myCamera.targetTexture = null;
}
}
private void TakeScreenshot(int widht, int height)
{
myCamera.targetTexture = RenderTexture.GetTemporary(widht, height, 16);
takeScreenshotOnNextFrame = true;
}
public static void TakeScreenshot_static(int width, int height)
{
instance.TakeScreenshot(width, height);
}
}