UnityEngine 中有三个截屏的方法:
声明的方法有:public static void CaptureScreenshot(string filename,int superSize);
public static void CaptureScreenshot(string filename, ScreenCapture.StereoScreenCaptureMode stereoCaptureMode);
使用技巧:
其中filename参数是指截图保存的路径,superSize是输出分辨率的倍数,而stereoCaptureMode,用立体渲染时采用左眼(LeftEye),右眼(RightEye),或者两者(BothEyes)模式。
截屏所保存的图片是.png格式。
2.ScreenCapture.CaptureScreenshotAsTexture 声明的方法有:public static Texture2D CaptureScreenshotAsTexture(int superSize);
public static Texture2D CaptureScreenshotAsTexture(ScreenCapture.StereoScreenCaptureMode stereoCaptureMode);
使用技巧:
此方法通过截屏返回一个Texture2D的贴图;
参数与上一个方法同名参数意义一样;
使用此截图发方法需要确保在帧渲染结束后调用,所以通常结合协程一起使用。
3.ScreenCapture.CaptureScreenshotIntoRenderTexture
声明的方法有:public static void CaptureScreenshotIntoRenderTexture(RenderTexture renderTexture);
使用技巧:
此方法将把截图返回一个RenderTexture对象;
使用此截图发方法需要确保在帧渲染结束后调用,所以通常结合协程一起使用。
该方法方便使用AsyncGPUReadback进行异步读取像素
例:
using UnityEngine;
using System.Collections;
using UnityEngine.Rendering;
public class ScreenCaptureIntoRenderTexture : MonoBehaviour
{
private RenderTexture renderTexture;
IEnumerator Start()
{
yield return new WaitForEndOfFrame();
renderTexture = new RenderTexture(Screen.width, Screen.height, 0);
ScreenCapture.CaptureScreenshotIntoRenderTexture(renderTexture);
AsyncGPUReadback.Request(renderTexture, 0, TextureFormat.RGBA32, ReadbackCompleted);
}
void ReadbackCompleted(AsyncGPUReadbackRequest request)
{
DestroyImmediate(renderTexture); //不需要保留渲染图,删除
using (var imageBytes = request.GetData<byte>())
{
// 可在此处获取像素后进行相关处理
}
}
}