using Blue; using UnityEngine; using UnityEngine.UI; namespace GHZLangChao { /// /// RawImage 转 Sprite /// public interface IRawImageForSpriteUtility : IUtility { Sprite SwitchSprite(RawImage rawImage); } public class RawImageForSpriteUtility : IRawImageForSpriteUtility { public Sprite SwitchSprite(RawImage rawImage) { // 获取RawImage的纹理 Texture2D rawTexture = TextureToTexture2D(rawImage.texture); // 创建一个新的纹理,用于截图 Texture2D screenshot = new Texture2D(rawTexture.width, rawTexture.height); // 截取RawImage的画面,并应用到新的纹理上 screenshot.SetPixels(rawTexture.GetPixels()); screenshot.Apply(); // 将截图应用到Image组件上 Sprite sprite = Sprite.Create(screenshot, new Rect(0, 0, screenshot.width, screenshot.height), new Vector2(0.5f, 0.5f)); return sprite; } /// /// 运行模式下Texture转换成Texture2D /// /// /// private Texture2D TextureToTexture2D(Texture texture) { Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false); RenderTexture currentRT = RenderTexture.active; RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 32); Graphics.Blit(texture, renderTexture); RenderTexture.active = renderTexture; texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0); texture2D.Apply(); RenderTexture.active = currentRT; RenderTexture.ReleaseTemporary(renderTexture); return texture2D; } } }