U3d中的Application.CaptureScreenshot方法,是一截全屏并保存在一张图片的方法
1、它是异步
如果你一定要在,程序中使用Application.CaptureScreenshot,且还要使用它截下的图片时,要注意:图片是在Application.CaptureScreenshot调用完成后一帧或更多久,才要被保存下来的,所以你要在Application.CaptureScreenshot调用完成后的下一要判断图片已经被保存好,才能去使用它。不然你会发现找不到图片的。
2、它保存的路径问题
在pc上可以给它传一个在Application.persistentDataPath下的全路径,
但在android和ios中只能给它传一个在Application.persistentDataPath下的相关路径
3.实现方法示例
#region 截屏
/// <summary>
/// 截取全屏图
/// </summary>
/// <param name="Path_save">图片保存路径</param>
/// <param name="func"></param>
public static void CapruerScreen(string Path_save, float waitTime,LuaFunction func)
{
if (Application.platform == RuntimePlatform.Android)
{
Main.Instance.StartCoroutine(CaptureScreenshot(Path_save, waitTime, func));
}
else if(Application.platform == RuntimePlatform.IPhonePlayer)//IOS平台
{
Main.Instance.StartCoroutine(Screenshot(new Rect(0, 0, Screen.width, Screen.height), Path_save,func));
}
}
/// <summary>
/// 简单截屏的方法
/// </summary>
/// <param name="path">保存路径</param>
/// <param name="func">回掉</param>
/// <returns></returns>
public static IEnumerator CaptureScreenshot(string path,float waitTime, LuaFunction func = null)
{
// 路径处理
// 注:path是一个在Application.persistentDataPath全路径
// Application.persistentDataPath这个方法的参数:
// 在pc呆传全路径
// 在android和ios上可能传Application.persistentDataPath下的相关路径
string newPath = path;
//非编辑器只取相对于沙盒的相对路径
if (Application.isMobilePlatform)
{
newPath = path.Replace(Application.persistentDataPath + "/", "");
}
Debuger.Log("newPath--->" + newPath);
Application.CaptureScreenshot(newPath);
float time = Time.time;
bool b = false;
yield return new WaitUntil(() =>
{
b = System.IO.File.Exists(path);
return b || ((Time.time - time) > waitTime);
});
string str = path;
if (b == false)
{
str = "-1";
}
if (func != null)
{
func.Call(str);
}
}
private static IEnumerator Screenshot(Rect rect, string path,LuaFunction func=null)
{
//等待渲染线程结束
yield return new WaitForEndOfFrame();
//初始化Texture2D
Texture2D mTexture = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGBA32, false);
//读取屏幕像素信息并存储为纹理数据
mTexture.ReadPixels(rect, 0, 0);
//应用
mTexture.Apply();
//将图片信息编码为字节信息
byte[] bytes = mTexture.EncodeToPNG();
//保存
System.IO.File.WriteAllBytes(path, bytes);
if (func != null&&File.Exists(path))
{
Debuger.Log("C#文件存在");
func.Call(path);
}
//如果需要可以返回截图
//return mTexture;
}
#endregion