1.新建screenshots 的脚本文件,挂到Canvas上面。
//下述为整个截屏代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System .IO ;
public class ScreenShot : MonoBehaviour {
// Use this for initialization
void Start () {
}
// 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) {
//把屏幕截图到一张贴图上
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);
}
}
}
2.在button下面的ON click()里面选中canvas组件,并选中此组件中的onscreenshot()方法。
3.下述不带Ui的方法是
先调用unity的UI界面
using UnityEngine.UI ;
//隐藏ui
this.GetComponentInChildren <Image >().enabled =false ;
this.GetComponentInChildren <Text >().enabled =false ;
//显示ui
this.GetComponentInChildren <Image >().enabled =true ;
this.GetComponentInChildren <Text >().enabled =true;