【Unity3D】實現Android截圖功能
阿新 • • 發佈:2022-03-20
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; using UnityEngine.UI; //指令碼功能:截圖,截圖帶UI public class ScreenShot : MonoBehaviour { public 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) {
//擷取螢幕,new一個貼圖放截圖Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); //讀取貼圖 texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0,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); } } }
- 指令碼命名為ScreenShot
- 把指令碼掛到某個object上,如canvas
- button按鈕on click()新增,選擇指令碼OnscreenShotClick()函式;
(程式碼存檔,以備不時之需)
不帶UI的,在以上程式碼修改
程式碼如下
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; using UnityEngine.UI; //指令碼功能:截圖 public class ScreenShot : MonoBehaviour { private Camera arCamera; // Start is called before the first frame update void Start() { arCamera = GameObject.Find("ARCamera").GetComponent<Camera>(); } // Update is called once per frame void Update() { } public 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) { RenderTexture rt = new RenderTexture(Screen.width, Screen.height, 1); arCamera.targetTexture = rt; arCamera.Render(); RenderTexture.active = rt; //new一個貼圖放截圖 Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); //讀取貼圖 texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0,0); texture.Apply(); arCamera.targetTexture = null; RenderTexture.active = null; Destroy(rt); //貼圖轉換成位元組陣列 byte[] bytes = texture.EncodeToPNG(); // string destination = "/sdcard/DCIM/ScreenShots"; // if (!Directory.Exists(destination)) { Directory.CreateDirectory(destination); } string pathSave = destination + "/" + fileName; File.WriteAllBytes(pathSave, bytes); } } }