最近要用Unity脚本在运行时截取相机图片,但是保存到本地后图片总是变暗。
结果发现是不可以预先创建一个rendertexture赋值给相机的targetTexture,必须在脚本里动态创建。参考链接
具体代码如下:
var oldT = RenderTexture.active;
var renderTextureTmp = RenderTexture.GetTemporary(1920, 1080, 32);
RenderTexture.active = cameraForScreenShot.targetTexture = renderTextureTmp;
cameraForScreenShot.Render();
var tmpTexture2D = new Texture2D(cameraForScreenShot.targetTexture.width, cameraForScreenShot.targetTexture.height);
tmpTexture2D.ReadPixels(new Rect(0, 0, cameraForScreenShot.targetTexture.width, cameraForScreenShot.targetTexture.height), 0, 0);
tmpTexture2D.Apply();
File.WriteAllBytes(path, tmpTexture2D.EncodeToPNG());
Destroy(tmpTexture2D);
RenderTexture.active = oldT;
cameraForScreenShot.targetTexture = null;
RenderTexture.ReleaseTemporary(renderTextureTmp);