Unity:截图

三种截图方式:

  1. 引擎自带的截图方法

  2. 矩形截图

  3. 相机截图

————————————————————————————————————————————

1. 引擎自带方法: ScreenCapture.CaptureScreenshot(“SavePath”);

2. 矩形截图:

1 private IEnumerator CaptureByRect(string fileName,Rect rect)
2     {
3         yield return new WaitForEndOfFrame();  //等当前帧渲染完了再截图
4         Texture2D mTexture = new Texture2D((int)rect.width, (int)rect.height,TextureFormat.RGB24,false);
5         mTexture.ReadPixels(rect, 0, 0);
6         mTexture.Apply();
7         byte[] bytes = mTexture.EncodeToPNG();
8         System.IO.File.WriteAllBytes(fileName, bytes);
9     }

2.5 拓展:截取鼠标选取的矩形区域

 1 private void Update()
 2     {
 3 
 4         if (Input.GetMouseButtonDown(0))
 5         {
 6             start = Input.mousePosition;
 7         }
 8         if (Input.GetMouseButtonUp(0))
 9         {
10             end = Input.mousePosition;
11 
12             Vector2 leftBottom = new Vector2(Mathf.Min(start.x, end.x), Mathf.Min(start.y, end.y));
13             rect = new Rect(leftBottom.x, leftBottom.y, Mathf.Abs(end.x - start.x), Mathf.Abs(end.y - start.y));
14             StartCoroutine(CaptureByRect(GetFilePath(), rect));
15         }
16     }

3. 相机截图

 1 private IEnumerator CaptureByCamera(Camera mCamera,Rect mRect,string fileName)
 2     {
 3         yield return new WaitForEndOfFrame();
 4         RenderTexture mRender = new RenderTexture((int)mRect.width, (int)mRect.height, 0);
 5         mCamera.targetTexture = mRender;  //给相机新建一个RenderTexture
 6         mCamera.Render();  //渲染一次相机
 7         RenderTexture.active = mRender;   //激活RenderTexture
 8         Texture2D mTexture = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
 9         mTexture.ReadPixels(rect, 0, 0);
10         mTexture.Apply();
11         mCamera.targetTexture = null;
12         Destroy(mRender);
13         byte[] bytes = mTexture.EncodeToPNG();
14         System.IO.File.WriteAllBytes(fileName, bytes);
15     }

 

posted @ 2021-12-05 17:34  番茄玛丽  阅读(446)  评论(0编辑  收藏  举报