U3D 三種實現截圖儲存精彩瞬間方式
阿新 • • 發佈:2019-02-12
在Unity3D,實現截圖的三種實現方式:
/// <summary> /// 使用Application類下的CaptureScreenshot()方法實現截圖 /// 優點:簡單,可以快速地擷取某一幀的畫面、全屏截圖 /// 缺點:不能針對攝像機截圖,無法進行區域性截圖 /// </summary> /// <param name="mFileName">M file name.</param> private void CaptureByUnity(string mFileName) { Application.CaptureScreenshot(mFileName,0); } /// <summary> /// 根據一個Rect型別來擷取指定範圍的螢幕 /// 左下角為(0,0) /// </summary> /// <param name="mRect">M rect.</param> /// <param name="mFileName">M file name.</param> private IEnumerator CaptureByRect(Rect mRect,string mFileName) { //等待渲染執行緒結束 yield return new WaitForEndOfFrame(); //初始化Texture2D Texture2D mTexture=new Texture2D((int)mRect.width,(int)mRect.height,TextureFormat.RGB24,false); //讀取螢幕畫素資訊並存儲為紋理資料 mTexture.ReadPixels(mRect,0,0); //應用 mTexture.Apply(); //將圖片資訊編碼為位元組資訊 byte[] bytes = mTexture.EncodeToPNG(); //儲存 System.IO.File.WriteAllBytes(mFileName, bytes); //如果需要可以返回截圖 //return mTexture; } private IEnumerator CaptureByCamera(Camera mCamera,Rect mRect,string mFileName) { //等待渲染執行緒結束 yield return new WaitForEndOfFrame(); //初始化RenderTexture RenderTexture mRender=new RenderTexture((int)mRect.width,(int)mRect.height,0); //設定相機的渲染目標 mCamera.targetTexture=mRender; //開始渲染 mCamera.Render(); //啟用渲染貼圖讀取資訊 RenderTexture.active=mRender; Texture2D mTexture=new Texture2D((int)mRect.width,(int)mRect.height,TextureFormat.RGB24,false); //讀取螢幕畫素資訊並存儲為紋理資料 mTexture.ReadPixels(mRect,0,0); //應用 mTexture.Apply(); //釋放相機,銷燬渲染貼圖 mCamera.targetTexture = null; RenderTexture.active = null; GameObject.Destroy(mRender); //將圖片資訊編碼為位元組資訊 byte[] bytes = mTexture.EncodeToPNG(); //儲存 System.IO.File.WriteAllBytes(mFileName,bytes); //如果需要可以返回截圖 //return mTexture; } }
接下來,我們來呼叫這三個方法實現一個簡單的截圖的例子:
//定義圖片儲存路徑 private string mPath1; private string mPath2; private string mPath3; //相機 public Transform CameraTrans; void Start() { //初始化路徑 mPath1=Application.dataPath+"\\ScreenShot\\ScreenShot1.png"; mPath2=Application.dataPath+"\\ScreenShot\\ScreenShot2.png"; mPath3=Application.dataPath+"\\ScreenShot\\ScreenShot3.png"; } //主方法,使用UGUI實現 void OnGUI() { if(GUILayout.Button("截圖方式1",GUILayout.Height(30))){ CaptureByUnity(mPath1); } if(GUILayout.Button("截圖方式2",GUILayout.Height(30))){ StartCoroutine(CaptureByRect(new Rect(0,0,1024,768),mPath2)); } if(GUILayout.Button("截圖方式3",GUILayout.Height(30))){ //啟用頂檢視相機 CameraTrans.camera.enabled=true; //禁用主相機 Camera.main.enabled=false; StartCoroutine(CaptureByCamera(CameraTrans.camera,new Rect(0,0,1024,768),mPath3)); } }