using Blue;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
namespace GHZLangChao
{
///
/// RawImage 转 Sprite
///
public interface IRawImageForSpriteUtility : IUtility
{
Sprite SwitchSprite(RawImage rawImage);
Texture2D TextureToTexture2D(Texture texture);
Sprite PngToSprite(string fullPath, int x, int y);
}
public class RawImageForSpriteUtility : IRawImageForSpriteUtility
{
public Sprite SwitchSprite(RawImage rawImage)
{
//SaveLocal(rawImage, "1", "0");
// 获取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
///
///
///
public 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;
}
///
/// 保存到本地
///
///
/// 某个步骤
/// 某个步骤的第几张图片
private void SaveLocal(RawImage rawImage, string Step, string id)
{
Texture2D texture2D = TextureToTexture2D(rawImage.texture);
byte[] bytes = texture2D.EncodeToPNG();
if (!Directory.Exists(Application.persistentDataPath + "/" + Step))
Directory.CreateDirectory(Application.persistentDataPath + "/" + Step);
string filename = Application.persistentDataPath + "/" + Step + "/" + id + ".png";
if (File.Exists(filename))
File.Delete(filename);
Debug.LogError(Application.persistentDataPath);
File.WriteAllBytes(filename, bytes);
}
///
/// IO方式 —— 将PNG转为Sprite精灵图片
///
/// 读取的PNG图片全路径:路径+文件名+后缀
/// 图片尺寸:宽
/// 图片尺寸:高
///
public Sprite PngToSprite(string fullPath, int x, int y)
{
using (FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.Read)) //自动双清
{
fs.Seek(0, SeekOrigin.Begin); //设定当前流的位置
byte[] bytes = new byte[fs.Length]; //创建文件长度缓冲区
fs.Read(bytes, 0, (int)fs.Length); //读取文件
Texture2D texture = new Texture2D(x, y); //创建Texture
texture.LoadImage(bytes);
return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.one / 2);
}
}
}
}