Unity3d中有时有截屏的需求,那如何截屏呢,代码如下:
/// <summary> /// 截屏 /// </summary> /// <param name="camera">截屏的摄像机</param> /// <param name="rect">图片大小</param> /// <returns>屏幕快照</returns> Texture2D CaptureCamera(Camera camera, Rect rect) { RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0); RenderTexture originRT = camera.targetTexture; // 临时把camera中的targetTexture替换掉 camera.targetTexture = rt; camera.RenderDontRestore(); // 手动渲染 camera.targetTexture = originRT; RenderTexture.active = rt; Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height); screenShot.ReadPixels(rect, 0, 0); // 读取的是 RenderTexture.active 中的像素 screenShot.Apply(); GameObject.Destroy(rt); RenderTexture.active = null; return screenShot; }
如何保存 Texture2D 图片:
static void SaveImage(Texture2D image, string path) { byte[] buffer = image.EncodeToPNG(); File.WriteAllBytes(path, buffer); }