🟥 Texture2D与Sprite互转
//转化后大小跟屏幕一样大 Sprite prite = Sprite.Create(要转换的Texture2D, new Rect(0, 0, Screen.width, Screen.height), new Vector2(0.5f, 0.5f)); //保持原有大小 Sprite prite = Sprite.Create(原图片, new Rect(0, 0, 原图片.width, 原图片.height), new Vector2(0.5f, 0.5f)); //sprite为图集中的某个子Sprite对象 var targetTex = new Texture2D((int)sprite.rect.width, (int)sprite.rect.height); var pixels = sprite.texture.GetPixels( (int)sprite.textureRect.x, (int)sprite.textureRect.y, (int)sprite.textureRect.width, (int)sprite.textureRect.height); targetTex.SetPixels(pixels); targetTex.Apply();
注意:
若想从Sprite转成Texture2D,如果你的Sprite是工程里的一张图片,
则该图片需勾选Read/Write Enabled 选项,否则会报 Texture ‘xxx’ is not readable 这个错误。
🟧 Texture和Texture2D转化
1️⃣ Texture转Texture2D
a、编辑器模式下
/// <summary> /// 编辑器模式下Texture转换成Texture2D /// </summary> /// <param name="texture"></param> /// <returns></returns> private Texture2D TextureToTexture2D(Texture texture) { Texture2D texture2d = texture as Texture2D; UnityEditor.TextureImporter ti = (UnityEditor.TextureImporter)UnityEditor.TextureImporter.GetAtPath(UnityEditor.AssetDatabase.GetAssetPath(texture2d)); //图片Read/Write Enable的开关 ti.isReadable = true; UnityEditor.AssetDatabase.ImportAsset(UnityEditor.AssetDatabase.GetAssetPath(texture2d)); return texture2d; }
b、运行模式下
/// <summary> /// 运行模式下Texture转换成Texture2D /// </summary> /// <param name="texture"></param> /// <returns></returns> 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; }
2️⃣ Texture2D转Texture
Texture2D->Sprite->Texture
🟨 sprite 和 bytes[] 的互相转换
1️⃣ 从sprite 转换到bytes[]
public byte[] GetByte(Sprite sp) { //转换成Texture Texture2D temp = sp.texture; //在转换成bytes byte[] photoByte = temp.EncodeToPNG(); return photoByte; }
2️⃣ 从bytes[] 转换到Sprite
public Sprite GetSprite(Byte[] bytes) { //先创建一个Texture2D对象,用于把流数据转成Texture2D Texture2D texture = new Texture2D(10, 10); texture.LoadImage(bytes);//流数据转换成Texture2D //创建一个Sprite,以Texture2D对象为基础 Sprite sp = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero); return sp; }
🟩 操作文件File类方法
读、写、移动、删除等 操作文件File类方法、文件操作相关类知识