Unity截屏的几种方式

2023/03 20 17:03
【载屏到文件】慢
ScreenCapture.CaptureScreenshot("xxx.png")
因为CPU要向GPU等待数据,非常卡,推荐


【全量载屏到纹理】快
// 先等一帧
yield return new WaitForEndOfFrame();
var screentex= RenderTexture.GetTemporary(Screen.width, Screen.height, 0, RenderTextureFormat.Default, "rt", false, false);
// 全量渲一帧
ScreenCapture.CaptureScreenshotIntoRenderTexture(rt);
// 获得平台差异
var rect = SystemInfo.graphicsUVStartsAtTop ? new Vector4(1.0f, -1.0f, 0.0f, 1.0f) : new Vector4(1.0f, 1.0f, 0.0f, 0.0f);
var displayTex = RenderTexture.GetTemporary(Screen.width, Screen.height, 0, RenderTextureFormat.Default, "displayTex", false, false, FilterMode.Bilinear);
// 画到指定纹理上
Graphics.Blit(screentex, displayTex, new Vector2(rect.x, rect.y), new Vector2(rect.z, rect.w));
RenderTexture.ReleaseTemporary(screentex);


【不带UI截图到RT】快
var mainCamera = GetComponent<Camera>();
if (mainCamera != null)
{
  var screentex= RenderTexture.GetTemporary(Screen.width, Screen.height, 0, RenderTextureFormat.Default, "rt", false, false);
  var lastTex = mainCamera.targetTexture;
  mainCamera.targetTexture = screentex;
  mainCamera.Render();
  mainCamera.targetTexture = lastTex;
}


【直接读】慢
Texture2D CaptureScreenshot2(Rect rect)
{
    Texture2D screenShot = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
    screenShot.ReadPixels(rect, 0, 0);
    screenShot.Apply();
    byte[] bytes = screenShot.EncodeToPNG();//然后将这些纹理数据,成一个png图片文件