ShareDataManager.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using ET;
  5. using FairyGUI;
  6. using UnityEngine;
  7. namespace GFGGame
  8. {
  9. class ShareDataManager : SingletonBase<ShareDataManager>
  10. {
  11. //当前分享
  12. public byte[] imageBytes;
  13. public Camera targetCamera; // 指定要读取的摄像机
  14. public string outputImagePath; // 输出图片的路径
  15. public void ShareImage(string imageUrl)
  16. {
  17. // 使用ShareSDK或其他分享插件来分享图片URL
  18. // 这里需要根据具体插件的API来实现分享功能
  19. }
  20. public void CaptureCameraToImage(bool isJump = true)
  21. {
  22. targetCamera = GameObject.Find("Stage Camera").GetComponent<Camera>();
  23. SetImageTargetPath();
  24. // 创建RenderTexture
  25. RenderTexture renderTexture = new RenderTexture(targetCamera.pixelWidth, targetCamera.pixelHeight, 24);
  26. targetCamera.targetTexture = renderTexture;
  27. // 强制摄像机渲染
  28. targetCamera.Render();
  29. // 创建Texture2D
  30. Texture2D screenShot = new Texture2D(targetCamera.pixelWidth, targetCamera.pixelHeight, TextureFormat.RGBA32, false);
  31. RenderTexture.active = renderTexture;
  32. screenShot.ReadPixels(new Rect(0, 0, targetCamera.pixelWidth, targetCamera.pixelHeight), 0, 0);
  33. screenShot.Apply();
  34. // 将RenderTexture中的像素数据读取到Texture2D
  35. screenShot.ReadPixels(new Rect(0, 0, targetCamera.pixelWidth, targetCamera.pixelHeight), 0, 0);
  36. screenShot.Apply();
  37. // 将Texture2D保存为图片
  38. imageBytes = screenShot.EncodeToPNG();
  39. // 保存到磁盘
  40. File.WriteAllBytes(outputImagePath, imageBytes);
  41. // 释放资源
  42. renderTexture.Release();
  43. Resources.UnloadUnusedAssets();
  44. targetCamera.targetTexture = null;
  45. Debug.Log("Camera capture saved to " + outputImagePath);
  46. if(isJump)
  47. {
  48. ViewManager.Show<ShareView>();
  49. }
  50. }
  51. public Texture2D ConvertBytesToTexture(byte[] imageBytes)
  52. {
  53. // 创建一个新的Texture2D对象
  54. Texture2D texture = new Texture2D(targetCamera.pixelWidth, targetCamera.pixelHeight); // 宽度和高度需要根据图片实际尺寸来设置
  55. texture.LoadImage(imageBytes); // 加载图片数据
  56. // 应用纹理设置
  57. texture.Apply();
  58. return texture;
  59. }
  60. private void SetImageTargetPath()
  61. {
  62. #if UNITY_EDITOR
  63. outputImagePath = Application.dataPath + "/StreamingAssets" + "/share.png";
  64. #elif UNITY_IPHONE
  65. outputImagePath = Application.dataPath+"/Ray"+"/share.png";
  66. #elif UNITY_android
  67. outputImagePath = "jar:file://"+Application.dataPath+"!/assets/"+"/share.png";
  68. #endif
  69. }
  70. }
  71. }