【Unity3D】实现Android截图功能
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); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!