unity實現遊戲界面截圖

在很多手遊中我們可能會留意到 當我們闖關成功或者失敗的時候
遊戲自動給我們截一個圖 然後提示我們可以分享朋友圈等等

我經過各方查找資料等
終於可以實現這個效果了 因爲中間有很多我們沒有深刻接觸過的類
所以代碼的意思還是沒有全部明白

下面開始實現
我們的思路是在文件夾中創建一個圖片
然後每次截圖之後 更新這個圖片的內容 之後再合適的時機我們可以用UGUI來表達出來
比如失敗或者成功的時候

void Update()
 {
  if (Input.GetKeyDown(KeyCode.KeypadEnter ))//檢測按下回車截圖
  {
   Camera camera = GameObject.Find("Main Camera").gameObject.GetComponent<Camera>();
   int ratio = 2;
   Rect rect = new Rect(0, 0, (int)Screen.width / ratio, (int)Screen.height / ratio);//圖片大小取決於ratio的大小
   Texture2D aa = ScreenShot(camera, rect);
  }
 }
 public Texture2D ScreenShot(Camera camera, Rect rect)
 {
  RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
  camera.targetTexture = rt;
  camera.Render();
  RenderTexture.active = rt;
  Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
  //顏色紋理格式,每個通道8位。
  screenShot.ReadPixels(rect, 0, 0);//從屏幕讀取像素到保存的紋理數據中。
  screenShot.Apply();//實際上應用所有以前的SetPixel和SetPixels更改。
  camera.targetTexture = null;
  RenderTexture.active = null;
  GameObject.Destroy(rt);
  byte[] bytes = screenShot.EncodeToPNG();//設置文件類型
  string filename = Application.dataPath + "/Resources/ScreenShot/screenshot.png";//存放路徑
  System.IO.File.WriteAllBytes(filename, bytes);//根據上邊的類型以及路徑寫入文件夾中去
#if UNITY_EDITOR
  UnityEditor.AssetDatabase.Refresh();//刷新,這步很關鍵,否則後面調用圖片時沒有。
#endif
  
  return screenShot;
 }

上邊是代碼 做項目的時候完全就可以把這個功能加上去
腳本自動尋找攝像機 文件夾等

注意 我們創建一個路徑/Resources/ScreenShot/screenshot.png"
不然不會報錯 而且也不會有效果

可以吧這個圖片的類型改成sprite(2d and UI)然後就可以給Image賦值了
之後我會更新裏邊的知識 比如RenderTexture 類等等

如果你也是unity愛好者 歡迎關注我的博客
我會在這裏持續更新我的學習過程
祝大家頭髮濃密 睡眠良好 財富自由
我是一名愛健身的準程序員

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章