IRawImageForSpriteUtility.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using Blue;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. namespace GHZLangChao
  5. {
  6. /// <summary>
  7. /// RawImage 转 Sprite
  8. /// </summary>
  9. public interface IRawImageForSpriteUtility : IUtility
  10. {
  11. Sprite SwitchSprite(RawImage rawImage);
  12. }
  13. public class RawImageForSpriteUtility : IRawImageForSpriteUtility
  14. {
  15. public Sprite SwitchSprite(RawImage rawImage)
  16. {
  17. // 获取RawImage的纹理
  18. Texture2D rawTexture = TextureToTexture2D(rawImage.texture);
  19. // 创建一个新的纹理,用于截图
  20. Texture2D screenshot = new Texture2D(rawTexture.width, rawTexture.height);
  21. // 截取RawImage的画面,并应用到新的纹理上
  22. screenshot.SetPixels(rawTexture.GetPixels());
  23. screenshot.Apply();
  24. // 将截图应用到Image组件上
  25. Sprite sprite = Sprite.Create(screenshot, new Rect(0, 0, screenshot.width, screenshot.height), new Vector2(0.5f, 0.5f));
  26. return sprite;
  27. }
  28. /// <summary>
  29. /// 运行模式下Texture转换成Texture2D
  30. /// </summary>
  31. /// <param name="texture"></param>
  32. /// <returns></returns>
  33. private Texture2D TextureToTexture2D(Texture texture)
  34. {
  35. Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
  36. RenderTexture currentRT = RenderTexture.active;
  37. RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 32);
  38. Graphics.Blit(texture, renderTexture);
  39. RenderTexture.active = renderTexture;
  40. texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
  41. texture2D.Apply();
  42. RenderTexture.active = currentRT;
  43. RenderTexture.ReleaseTemporary(renderTexture);
  44. return texture2D;
  45. }
  46. }
  47. }