截屏(截图)在 Unity 中有三种常见方式。

方式一:使用 Application.CaptureScreenshot

最简单的方式是直接调用 Application 提供的 API:

Application.CaptureScreenshot(Application.dataPath + "/11.png");

方式二:使用 Texture2D.ReadPixels

利用 Texture2D 提供的 ReadPixels 函数可以手动读取像素并保存。注意:该函数必须在每帧渲染完成后才能调用,否则会抛出以下异常:

ReadPixels was called to read pixels from system frame buffer, while not inside drawing frame.

该函数从 RenderTexture.active 中读取数据。官方文档说明如下:

This will copy a rectangular pixel area from the currently active RenderTexture or the view (specified by the source parameter) into the position defined by destX and destY. Both coordinates use pixel space — (0,0) is lower left.

示例协程实现:

IEnumerator Cap()
    {
        yield return new WaitForEndOfFrame();

        Texture2D tex = new Texture2D(Screen.width, Screen.height);

        tex.ReadPixels(new Rect(Vector2.zero, new Vector2(Screen.width, Screen.height)), 0, 0);
        var raw = tex.EncodeToPNG();
        string filename = Application.dataPath + "/111.png";

        System.IO.File.WriteAllBytes( filename, raw);
    }

方式三:摄像机渲染到 RenderTexture

摄像机可以将画面渲染到 RenderTexture,再对其执行截图保存相关操作。