Unity實現截圖以及根據相機畫面截圖
阿新 • • 發佈:2020-04-20
在遊戲開發和軟體開發中,經常需要截圖的功能,分帶UI的截圖和不帶UI的截圖功能。程式碼如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; public static class ScreenShotForCamera{ public static void CaptureScreen(string _path = null) { if (_path == null) _path = "Screenshot.png"; Application.CaptureScreenshot(_path,0); } public static Texture2D CaptureScreen(Rect rect,bool _isCreatePhoto = false,string _path = null) { // 先建立一個的空紋理,大小可根據實現需要來設定 Texture2D screenShot = new Texture2D((int)rect.width,(int)rect.height,TextureFormat.RGB24,false); // 讀取螢幕畫素資訊並存儲為紋理資料, screenShot.ReadPixels(rect,0); screenShot.Apply(); // 然後將這些紋理資料,成一個png圖片檔案 if (_isCreatePhoto) { if(_path == null) _path = Application.dataPath + "/Screenshot.png"; byte[] bytes = screenShot.EncodeToPNG(); string filename = _path; System.IO.File.WriteAllBytes(filename,bytes); Debug.Log(string.Format("截圖了一張圖片: {0}",filename)); } // 最後,我返回這個Texture2d物件,這樣我們直接,所這個截圖圖示在遊戲中,當然這個根據自己的需求的。 return screenShot; } // public static Texture2D CaptureCamera(ref Camera _camera,Rect _rect,int _destX,int _destY,string _path = null) { RenderTexture renderTexture = new RenderTexture((int)_rect.width,(int)_rect.height,24,RenderTextureFormat.ARGB32); _camera.targetTexture = renderTexture; _camera.Render(); // 啟用這個renderTexture,並從中中讀取畫素 RenderTexture.active = _camera.targetTexture; Texture2D screenShot = new Texture2D((int)_rect.width,TextureFormat.ARGB32,false); screenShot.ReadPixels(_rect,_destX,_destY); //從(_destX,_destY)座標開始讀取_rect大小的圖片 screenShot.Apply(); //重置引數 //_camera.targetTexture = null; RenderTexture.active = null; //GameObject.Destroy(renderTexture); //生成PNG圖片 if (_isCreatePhoto) { if (_path == null) _path = Application.dataPath + "/Screenshot.png"; byte[] bytes = screenShot.EncodeToPNG(); string filename = _path; System.IO.File.WriteAllBytes(filename,bytes); Debug.Log(string.Format("截圖了一張照片: {0}",filename)); } return screenShot; } }
小編再為大家分享一段:Unity實現截圖功能,希望可以幫到大家
public class ScreenShot : MonoBehaviour { void OnScreenShotClick() { //得到當前系統時間 System.DateTime now = System.DateTime.Now; string times = now.ToString(); //去掉前後空格 times = times.Trim(); //將斜槓替換成橫槓 times = times.Replace("/","-"); string fileName = "ARScreenShot" + times + ".png"; //判斷該平臺是否為安卓平臺 if (Application.platform == RuntimePlatform.Android) { //引數依次為 螢幕寬度 螢幕高度 紋理格式 是否使用對映 Texture2D texture = new Texture2D(Screen.width,Screen.height,false); //讀取貼圖 texture.ReadPixels(new Rect(0,Screen.width,Screen.height),0); //應用截圖 texture.Apply(); //將物件序列化 byte[] bytes = texture.EncodeToPNG(); //設定儲存到的手機資料夾路徑 string destination = "/sdcard/DCIM/Screenshots"; //如果不存在該資料夾 if (!Directory.Exists(destination)) { //建立該資料夾 Directory.CreateDirectory(destination); } string pathSave = destination + "/" + fileName; File.WriteAllBytes(pathSave,bytes); } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。