Unity截屏

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

1 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图片。

原文地址:https://www.cnblogs.com/July7th/p/4606918.html