/// <summary>
/// 截屏
/// 缺点:此方法截屏时会卡顿
/// </summary>
public static string CaptureScreenshot(string imageName = null)
{
if (string.IsNullOrEmpty(imageName))
imageName = "screenshot";
Application.CaptureScreenshot(imageName + ".png");
return GetCaptureScreenshotPath(imageName);
}
/// <summary>
/// 截屏
/// </summary>
public static IEnumerator CaptureScreenshot(string filePath, Action<string, Texture2D> callback = null)
{
Rect rect = new Rect();
rect.width = Screen.width;
rect.height = Screen.height;
//等待渲染线程结束
yield return new WaitForEndOfFrame();
Texture2D texture = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
//读取屏幕像素
texture.ReadPixels(rect, 0, 0);
//应用
texture.Apply();
//保存纹理
byte[] bytes = null;
if (filePath.EndsWith(".png"))
{
bytes = texture.EncodeToPNG();
}
else if (filePath.EndsWith(".jpg"))
{
bytes = texture.EncodeToJPG();
}
else
{
if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath);
filePath += "/screenshot_" + DateTime.Now.ToFileTime() + ".jpg";
bytes = texture.EncodeToJPG();
}
File.WriteAllBytes(filePath, bytes);
callback?.Invoke(filePath, texture);
yield return texture;
}
// 获取相册路径
public static string GetAlbumPath()
{
string path = Application.persistentDataPath;
path = path.Substring(0, path.IndexOf("Android/data/"));
path += "DCIM";
return path;
}
/// <summary>
/// 获取通过Application.CaptureScreenshot("xxx.png")截屏文件路径
/// </summary>
/// <param name="imageName">图片名</param>
/// <returns></returns>
public static string GetCaptureScreenshotPath(string imageName)
{
string imagePath = Application.dataPath;
if(Application.platform == RuntimePlatform.Android)
imagePath = Application.persistentDataPath;
else if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.OSXPlayer)
imagePath = string.Format("file://{0}", Application.persistentDataPath);
else if (Application.platform == RuntimePlatform.WindowsPlayer)
imagePath = Application.dataPath;
else if (Application.platform == RuntimePlatform.WindowsEditor)
imagePath = imagePath.Replace("/Assets", "");
return string.Format("{0}/{1}.png", imagePath, imageName);
}