Unity 相机截图功能

Unity 相机截图功能

其实Unity 内部集成的有全屏截图功能,但是鉴于其功能的局限性,所以写下这篇博客

  • 直接给出整理好的截图代码,如下:

   /// <summary>
   /// 截取指定Camera指定区域画面,并保存到本地
   /// </summary>
   /// <param name="rect">截取区域 new Rect(x轴偏移,y轴偏移,截取长度,截取高度)</param>
   /// <param name="camera">指定相机</param>
   /// <param name="path">截取图片保存路径 默认为空不需要保存到本地</param>
   public IEnumerator Shot( Rect rect, Camera camera=null, string path = null)
   {
       if (!camera)//如果不选定截图相机则默认为主相机截图
       {
           camera = Camera.main;
       }
       RenderTexture rt = new RenderTexture((int)(Screen.width), (int)(Screen.height), 0);//先设置一个RenderTexture,大小为屏幕分辨率
       camera.targetTexture = rt;
       camera.Render();//手动开启截图相机的渲染
       RenderTexture.active = rt;//激活这个RenderTexture

       //验算是否超出屏幕渲染,如果超出则取最大边界
       float width = rect.width + rect.x > Screen.width ? Screen.width - rect.x : rect.width;
       float height = rect.height + rect.y > Screen.height ? Screen.height - rect.y : rect.height;


       //新建一个模板Texture2D等待相机渲染图像,设定Textrue2D的大小为我们需要的大小
       Texture2D screenShot = new Texture2D((int)width, (int)height, TextureFormat.ARGB32, false);
       yield return new WaitForEndOfFrame();

       // 注:这个时候,它是从RenderTexture.active中读取像素
       screenShot.ReadPixels(new Rect(rect.x, rect.y, width, height), 0, 0);
       screenShot.Apply();//保存像素信息
       // 重置相关参数,以使用camera继续在屏幕上显示

       //还原各项截图前得初始设定
       camera.targetTexture = null;
       RenderTexture.active = null;
       Destroy(rt);

       if (path != null)
       {
           //生成png图片保存至目标路径
           byte[] bytes = screenShot.EncodeToPNG();
           File.WriteAllBytes(path, bytes);
       }
   }

之所以把截图代码写在协程里面,是因为,在创建Textrue2D的时候有一个很小的时间差,如果用普通方法,则有可能会出现模板Texture2D读取像素的时候报空,故采取协程写法

  • 使用:(上面的注释很清楚,直接简单示范使用)
//截取全屏,保存至本地路径
StartCoroutine(Shot(new Rect(0, 0,Screen.width,Screen.height),null,Application.streamingAssetsPath + "/screenShot.png"));

发布了11 篇原创文章 · 获赞 2 · 访问量 334

猜你喜欢

转载自blog.csdn.net/weixin_42498461/article/details/103970354