Unity遊戲開發之“屏幕截圖”

在unity遊戲開發中,可能會遇到在遊戲中截屏的效果。這兒提供兩種截屏方法。(方法二提供顯示截圖縮略圖代碼)

       方法一:在unity的API中,unity給我們提供了一個現成的API  :  Application.CaptureScreenshot(imagename)。但是這個API雖然簡單,在PC、mac運用沒有多大的影響,但是如果是在移動平臺上使用的話就顯得相當的吃力,因爲它會消耗我們很大的CUP,所以你在移動端使用它截屏的時候會發現很長一段的卡頓現象。但是不得不說使用起來非常的方便,但是在我們使用這個API截圖後的截圖存放在哪兒呢?很多新朋友可能不是很清楚,當然不同的平臺它的存放路徑是有差別的。下面是各個平臺的截圖存放路徑:

             Application.CaptureScreenshot(screencapture.png)

            if(Application.platform==RuntimePlatform.Android || Application.platform==RuntimePlatform.IPhonePlayer)  

                 imagePath=Application.persistentDataPath;  

            else if(Application.platform==RuntimePlatform.WindowsPlayer)  

                 imagePath=Application.dataPath;  

           else if(Application.platform==RuntimePlatform.WindowsEditor)

            {  

                 imagePath=Application.dataPath;  

                 imagePath= imagePath.Replace("/Assets",null);  

             }   

            imagePath = imagePath + "/screencapture.png";

         如果你想要你的遊戲中顯示你截圖的縮略圖,那麼這種方法不是一個好方法,因爲你                要用 WWW去加載你剛纔的截圖,這會消耗你一部分的時間。    

      方法二:通過讀取屏幕緩存然後轉化爲Png圖片進行截圖。(當然截圖存儲路徑你可以自己設置)

                IEnumerator GetCapture()

                {

                        yield return new WaitForEndOfFrame();

                        int width = Screen.width;

                        int height = Screen.height;

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

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

                        byte[] imagebytes = tex.EncodeToPNG();//轉化爲png圖

                        tex.Compress(false);//對屏幕緩存進行壓縮

                        image.mainTexture = tex;//對屏幕緩存進行顯示(縮略圖)

                        File.WriteAllBytes(Application.dataPath + "/screencapture.png",imagebytes);//存儲png圖

                }

        有興趣的朋友可以試試這兩種截圖方法的性能和可用性。

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