Camera有一个targetTexture属性,在设置了targetTexture后,Camera会在渲染时将其屏幕上的图像渲染到targetTexture上,可以使用快照实现镜头切换等特效
具体实现:
private Texture2D CaptureCamera(Camera camera, Rect rect)
{
RenderTexture buffer = RenderTexture.GetTemporary((int)rect.width, (int)rect.height, 1);
camera.targetTexture = buffer;
camera.Render();
// 激活这个rt, 并从中中读取像素。
RenderTexture.active = buffer;
Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
screenShot.Apply();
// 重置相关参数,以使用 camera 继续在屏幕上显示
camera.targetTexture = null;
RenderTexture.active = null;
GameObject.Destroy(buffer);
return screenShot;
}