网上有很多资料,我就不一一赘述了,这就做个代码记录一下,截图并且保存到本地文件夹下
代码如下:
/// <summary>
/// 对相机截屏,并保存
/// </summary>
/// <returns>The camera.</returns>
/// <param name="camera">Camera.</param>
/// <param name="rect">Rect.</param>
public void CaptrueCamera(Camera camera, Rect rect)
{
RenderTexture startTex = camera.targetTexture;
// 创建一个RenderTexture对象
RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
// 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
camera.targetTexture = rt;
camera.Render();
// 激活这个rt, 并从中中读取像素。
RenderTexture.active = rt;
Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
screenShot.Apply();
// 重置相关参数,以使用camera继续在屏幕上显示
camera.targetTexture = startTex;
//ps: camera2.targetTexture = null;
RenderTexture.active = null; // JC: added to avoid errors
GameObject.Destroy(rt);
string formatType = ".png";
//string formatTime = DateTime.Now.ToString();
//formatTime = formatTime.Replace('/', '-').Replace(' ', '-').Replace(':', '-').ToString();
// 最后将这些纹理数据,成一个png图片文件
byte[] bytes = screenShot.EncodeToPNG();
string filename = null;
#if UNITY_ANDROID
filename = Application.persistentDataPath + "/" + formatTime + formatType;
Debug.Log("android!");
#elif UNITY_IPHONE
filename = Application.persistentDataPath + "/" + formatTime + formatType;
Debug.Log("ios");
#elif UNITY_EDITOR
//string file = loadFile();
//filename = Application.dataPath + "/" + file + formatType;
Debug.Log("editor");
#endif
string path;
int index;
loadFile(out path, out index);
// 截图保存图片
if (path != null)
{
string file = path;
file = file + formatType;
filename = path.Substring(index);
System.IO.File.WriteAllBytes(file, bytes);
StartCoroutine(SaveSucess());
Debug.Log(string.Format("截屏了一张照片: {0}", filename));
}
//Sprite sprite = Sprite.Create(screenShot, new Rect(0, 0, screenShot.width, screenShot.height), new Vector2(0.5f, 0.5f));
//return sprite;
}
IEnumerator SaveSucess()
{
tips.text = "保存成功";
yield return new WaitForSeconds(3.0f);
tips.gameObject.SetActive(false);
}
void loadFile(out string path,out int index)
{
OpenFileName openFileName = new OpenFileName();
openFileName.structSize = Marshal.SizeOf(openFileName);
//openFileName.filter = "All files (*.*)|*.*";
openFileName.filter = "(*.png,)|*.png;|All files(*.*)|*.*";
openFileName.file = new string(new char[256]);
openFileName.maxFile = openFileName.file.Length;
openFileName.fileTitle = new string(new char[64]);
openFileName.maxFileTitle = openFileName.fileTitle.Length;
openFileName.initialDir = Application.streamingAssetsPath.Replace('/', '\\');//默认路径
openFileName.title = "保存项目";
openFileName.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008;
if (LocalDialog.GetSaveFileName(openFileName))
{
int indexNum = openFileName.file.LastIndexOf(openFileName.fileTitle);
path= openFileName.file;
Debug.Log(openFileName.file);
index = indexNum;
}
else
{
path = null;
index = 0;
}
}
基本上只要调用就可以了