PhotographSaveView.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Collections;
  3. using System.IO;
  4. using FairyGUI;
  5. using UI.DressUp;
  6. using UnityEngine;
  7. namespace GFGGame
  8. {
  9. public class PhotographSaveView : BaseView
  10. {
  11. private UI_PhotographSaveUI _ui;
  12. protected override void OnInit()
  13. {
  14. base.OnInit();
  15. packageName = UI_PhotographUI.PACKAGE_NAME;
  16. _ui = UI_PhotographSaveUI.Create();
  17. viewCom = _ui.target;
  18. isfullScreen = true;
  19. _ui.m_btnClose.onClick.Add(this.Hide);
  20. _ui.m_btnSave.onClick.Add(this.OnClickBtnSave);
  21. }
  22. protected override void OnShown()
  23. {
  24. base.OnShown();
  25. Texture2D tex = this.viewData as Texture2D;
  26. _ui.m_imgRes.texture = new NTexture(tex);
  27. float width = _ui.m_imgBorder.width;
  28. float height = width * tex.height / tex.width;
  29. _ui.m_imgRes.SetSize(width, height);
  30. _ui.m_imgBorder.SetSize(width, height + 12);
  31. }
  32. private void OnClickBtnSave()
  33. {
  34. string path = Application.persistentDataPath;
  35. Debug.Log("文件路径path:" + path);
  36. #if UNITY_ANDROID
  37. path = Application.persistentDataPath.IndexOf("Android") > 0 ? path.Substring(0, Application.persistentDataPath.IndexOf("Android")) + "Pictures/万世镜" : path + "/Pictures/万世镜";
  38. #endif
  39. //判断目录是否存在,不存在则会创建目录
  40. if (!Directory.Exists(path))
  41. {
  42. try
  43. {
  44. Directory.CreateDirectory(path);
  45. }
  46. catch (Exception exception)
  47. {
  48. throw new Exception("创建文件夹失败, error:" + exception.Message);
  49. }
  50. }
  51. string fileName = DateUtils.Instance.GetCurTime() + ".png";
  52. path = path + "/" + fileName;
  53. Debug.Log("文件路径:" + path);
  54. Texture2D tex = this.viewData as Texture2D;
  55. byte[] bytes = tex.EncodeToPNG();//将纹理数据,转化成一个png图片
  56. try
  57. {
  58. FileStream newFs = new FileStream(path, FileMode.Create, FileAccess.Write);
  59. newFs.Write(bytes, 0, bytes.Length);
  60. newFs.Close();
  61. newFs.Dispose();
  62. }
  63. catch (Exception ex)
  64. {
  65. throw new Exception("保存失败, error:" + ex.Message);
  66. }
  67. // string path = Application.persistentDataPath.Substring(0, Application.persistentDataPath.IndexOf("Android"));
  68. // File.WriteAllBytes(path, bytes);
  69. Timers.inst.StartCoroutine(GetSaveState(path));// ();
  70. }
  71. private IEnumerator GetSaveState(string path)
  72. {
  73. yield return new WaitForEndOfFrame();
  74. if (File.Exists(path))
  75. {
  76. PromptController.Instance.ShowFloatTextPrompt("保存成功");
  77. }
  78. }
  79. protected override void OnHide()
  80. {
  81. base.OnHide();
  82. }
  83. public override void Dispose()
  84. {
  85. base.Dispose();
  86. }
  87. }
  88. }