untiy学习之屏幕截图各种方式

本文详细介绍Unity中三种截图方法:直接使用Unity内置函数、通过屏幕缓存转化为PNG图片、截图特定相机自定义内容。并扩展介绍鼠标画区域截取的实现思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方式一:直接使用unity自带的截图函数

Application.CaptureScreenshot(“imagename”)

 

保存路径:

  1.        在PC上保存路径为Application.dataPath(项目所在的路径)
  2.        在安卓或者Iphone平台上保存路径为Application.persistentDataPath(游戏里保存数据时放的一个持久数据目录)

 

优点:简单粗暴

缺点:PC、Mac上正常,但是在移动平台上会出现卡顿现象。

 

 

方式二:通过屏幕缓存转化为Png图片进行截图。

 

  IEnumerator GetCapture()

  {

      //等待所有的摄像机跟GUI渲染完成

      yield return new WaitForEndOfFrame();

 

      int width = Screen.width;

 

      int height = Screen.height;

 

      Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);

 

      //如果 recalculateMipMaps 设置为真,这个贴图的mipmaps就会更新 如果 recalculateMipMaps设置为假,你需要调用Apply重新计算它们

      tex.ReadPixels(new Rect(0, 0, width, height), 0, 0, true);

 

      byte[] imagebytes = tex.EncodeToPNG();//转化为png图

 

      tex.Compress(false);//对屏幕缓存进行压缩

      System.IO.File.WriteAllBytes(Application.dataPath + "/screencapture" + shotID + ".png", imagebytes);//存储png图

 

  }

方式三:截图特定相机,自定义截图内容

  public void ShotThree()

  {

     

      RenderTexture renderTex = new RenderTexture(Screen.width,Screen.height,0);

 

      if (shotCamera.targetTexture == null)

      {

          shotCamera.targetTexture = renderTex;

      }

      //手动渲染相机。

      shotCamera.Render();

 

      //所有的渲染将进入激活的RenderTexture,如果活动的RenderTexture为null,所有的东西都被渲染到主窗口

      RenderTexture.active = renderTex;

 

      Texture2D screenShot = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);

  screenShot.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);//     

screenShot.Apply();

 

 

      // 重置相关参数,以使用camera继续在屏幕上显示 

      shotCamera.targetTexture = null;

      RenderTexture.active = null; // JC: added to avoid errors 

      Destroy(renderTex);

      // 最后将这些纹理数据,成一个png图片文件 

      byte[] bytes = screenShot.EncodeToPNG();

 

      string filename = Application.dataPath + "/Screenshot.png";

 

      shotID++;

      System.IO.File.WriteAllBytes(shotPath + "/screencapture" + shotID + ".png", bytes);

  }

 

扩展方式四:鼠标画区域截取,实现方式同上,核心思想为记录鼠标按下跟抬起的点,算出矩形,读取该矩形范围内的像素保存为png图片。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Maorin

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

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

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

打赏作者

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

抵扣说明:

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

余额充值