jietu.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using SUIFW;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using UnityEditor;
  6. using UnityEngine;
  7. using UnityEngine.UI;
  8. public class jietu : MonoBehaviour
  9. {
  10. private Camera screenShotCamera;
  11. private Texture shots;
  12. public Transform imageParent;
  13. public RawImage jietuBG;
  14. private void Start()
  15. {
  16. if (UIMaskMgr.GetInstance()._UICamear)
  17. {
  18. screenShotCamera = UIMaskMgr.GetInstance()._UICamear;
  19. }
  20. }
  21. public void ClickJietu()
  22. {
  23. if (screenShotCamera && RoomMainForms.Instance)
  24. {
  25. //Debug.Log("截屏");
  26. RoomMainForms.Instance.CkickOnJieTuBtn();
  27. PaintLine.canUse = false;
  28. Rect rect = new Rect(0, 0, Screen.width, Screen.height);
  29. shots = ScreenShot(screenShotCamera, rect);
  30. }
  31. }
  32. // <summary>
  33. /// 传入一个 RectTransform 区域!, 就不把资格区域的图像保存下来
  34. /// </summary>
  35. /// <param name="rect"></param>
  36. public Texture2D ScreenShot(Camera camera, Rect rect)
  37. {
  38. RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
  39. camera.targetTexture = rt;
  40. camera.Render();
  41. RenderTexture.active = rt;
  42. Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
  43. screenShot.ReadPixels(rect, 0, 0);
  44. screenShot.Apply();
  45. camera.targetTexture = null;
  46. RenderTexture.active = null;
  47. GameObject.Destroy(rt);
  48. //Debug.Log("截图成功");
  49. /*
  50. byte[] bytes = screenShot.EncodeToPNG();
  51. string filename = Application.dataPath + "/Resources/ScreenShot/screenshot.png";//存放路径
  52. File.WriteAllBytes(filename, bytes);
  53. //TextureImporter texture = AssetImporter.GetAtPath(filename) as TextureImporter;
  54. //texture.textureType = TextureImporterType.Sprite;*/
  55. #if UNITY_EDITOR
  56. UnityEditor.AssetDatabase.Refresh();//刷新,这步很关键,否则后面调用图片时没有。
  57. #endif
  58. Invoke("CreateImage", 0.5f);
  59. return screenShot;
  60. }
  61. void CreateImage()//在canvas显示截屏后的图片
  62. {
  63. if (RoomMainForms.Instance)
  64. {
  65. RoomMainForms.Instance.ShowShotsAllBtn();
  66. }
  67. GameObject Im = new GameObject();
  68. Im.name = "jieping";
  69. Im.transform.SetParent(imageParent, false);
  70. RawImage rawImage = Im.AddComponent<RawImage>();//添加RawImage属性
  71. if (shots != null && rawImage)
  72. {
  73. rawImage.texture = shots;//将图片赋到RawImage上
  74. rawImage.rectTransform.sizeDelta = new Vector2(shots.width, shots.height);//定义图片最初显示尺寸
  75. rawImage.rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0, 0);
  76. rawImage.rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, 0);
  77. }
  78. }
  79. }