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"));

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

司军礼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值