關於Unity實現AR功能(三)AR手機截圖

 1 /*************************************************
 2  * 項目名稱:AR截圖
 3  * 腳本建立人:魔卡
 4  * 腳本建立時間:2018.10.02
 5  * 腳本功能:截取當前手機界面圖片到系統相冊截圖中
 6  * ***********************************************/
 7 using System.Collections;
 8 using System.Collections.Generic;
 9 using System.IO;
10 using UnityEngine;
11 using UnityEngine.UI;
12 
13 public class ScreenShot : MonoBehaviour
14 {
15     private Button m_screenShotBtn;//截屏按鈕
16 
17     void Awake()
18     {
19         //初始化
20         m_screenShotBtn = transform.Find("ScreenShotBtn").GetComponent<Button>();
21         m_screenShotBtn.onClick.AddListener(OnScreenShotBtnClick);
22     }
23 
24     /// <summary>
25     /// 自定義截屏功能,截屏按鈕點擊觸發
26     /// </summary>
27     public void OnScreenShotBtnClick()
28     {
29 
30 
31         //使用當前時間做爲圖片名稱
32         System.DateTime tNowTime = System.DateTime.Now;
33         string tTime = tNowTime.ToString();
34         //去除兩邊空格
35         tTime = tTime.Trim();
36         //將「/」用「-」代替
37         tTime = tTime.Replace("/", "-");
38 
39         //存儲爲png格式的
40         string tFileName = "ARScreenShot" + tTime + ".png";
41 
42         //判斷當前運行環境
43         if (Application.platform == RuntimePlatform.Android)
44         {
45             //生成一個Texture2D (參數爲:寬,高,紋理,是否使用映射)
46             Texture2D tTexture2D = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
47             //讀取Texture2D到自己上
48             tTexture2D.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
49             //圖片應用一下
50             tTexture2D.Apply();
51 
52             //將圖片轉換爲二進制進行寫入
53             byte[] tBytes = tTexture2D.EncodeToPNG();
54 
55             //寫入地址
56             //此處注意,寫入的地址是當前手機截屏的默認地址,其餘地址也能夠存儲可是在圖冊中不會顯示出來
57             string tDestination = "/sdcard/DCIM/Screenshots";
58 
59             //判斷當前文件夾是否存在,不存在則進行建立
60             if (!Directory.Exists(tDestination))
61             {
62                 Directory.CreateDirectory(tDestination);
63             }
64 
65             //截圖存儲路徑名
66             string tSavePath = tDestination + "/" + tFileName;
67 
68             File.WriteAllBytes(tSavePath, tBytes);
69         }
70     }
71 }

效果圖以下:spa

相關文章
相關標籤/搜索