Shot.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using UnityEngine;
  6. public class Shot : MonoBehaviour
  7. {
  8. /// <summary>
  9. /// 保存截屏图片,并且刷新相册(Android和iOS)
  10. /// </summary>
  11. /// <param name="name">若空就按照时间命名</param>
  12. public void CaptureScreenshot()
  13. {
  14. string _name = "";
  15. if (string.IsNullOrEmpty(name))
  16. {
  17. _name = "Screenshot_" + GetCurTime() + ".png";
  18. }
  19. //编辑器下
  20. //string path = Application.persistentDataPath + "/" + _name;
  21. //Application.CaptureScreenshot(path, 0);
  22. //EDebug.Log("图片保存地址" + path);
  23. //Android版本
  24. StartCoroutine(CutImage(_name));
  25. Debug.Log("图片保存地址" + _name);
  26. }
  27. //截屏并保存
  28. IEnumerator CutImage(string name)
  29. {
  30. //图片大小
  31. Texture2D tex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, true);
  32. yield return new WaitForEndOfFrame();
  33. tex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, true);
  34. tex.Apply();
  35. yield return tex;
  36. byte[] byt = tex.EncodeToPNG();
  37. string path = Application.persistentDataPath.Substring(0, Application.persistentDataPath.IndexOf("Android"));
  38. File.WriteAllBytes(path + "/Pictures/Screenshots/" + name, byt);
  39. string[] paths = new string[1];
  40. paths[0] = path;
  41. ScanFile(paths);
  42. yield break;
  43. }
  44. //刷新图片,显示到相册中
  45. void ScanFile(string[] path)
  46. {
  47. using (AndroidJavaClass PlayerActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
  48. {
  49. AndroidJavaObject playerActivity = PlayerActivity.GetStatic<AndroidJavaObject>("currentActivity");
  50. using (AndroidJavaObject Conn = new AndroidJavaObject("android.media.MediaScannerConnection", playerActivity, null))
  51. {
  52. Conn.CallStatic("scanFile", playerActivity, path, null, null);
  53. }
  54. }
  55. }
  56. /// <summary>
  57. /// 获取当前年月日时分秒,如201803081916
  58. /// </summary>
  59. /// <returns></returns>
  60. string GetCurTime()
  61. {
  62. return (DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString());
  63. }
  64. }