using System.IO;using UnityEngine;using UnityEditor; public class TestSaveSprite{ [MenuItem("LLWH/SpriteSplit")] public static void SpriteSlice() { Te ...
using System.IO;
using UnityEngine;
using UnityEditor;
public class TestSaveSprite
{
[MenuItem("LLWH/SpriteSplit")]
public static void SpriteSlice()
{
Texture2D image = Selection.activeObject as Texture2D; // 得到選中的圖集 該圖集事先已經被修改屬性
string rootPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(image)); //文件所在的路徑
string path = rootPath + "/" + image.name + ".PNG"; //Assets/Resources/UI/XXX.png
TextureImporter texImp = AssetImporter.GetAtPath(path) as TextureImporter;
AssetDatabase.CreateFolder(rootPath, image.name);
// 遍歷圖集中每一張小圖,並使用文件IO寫入到同級目錄的文件夾中
foreach (SpriteMetaData metaData in texImp.spritesheet)
{
Texture2D myimage = new Texture2D((int)metaData.rect.width, (int)metaData.rect.height);
for (int y = (int)metaData.rect.y; y < metaData.rect.y + metaData.rect.height; y++)
{
for (int x = (int)metaData.rect.x; x < metaData.rect.x + metaData.rect.width; x++)
myimage.SetPixel(x - (int)metaData.rect.x, y - (int)metaData.rect.y, image.GetPixel(x, y));
}
if (myimage.format != TextureFormat.ARGB32 && myimage.format != TextureFormat.RGB24)
{
Texture2D newTexture = new Texture2D(myimage.width, myimage.height);
newTexture.SetPixels(myimage.GetPixels(0), 0);
myimage = newTexture;
}
var pngData = myimage.EncodeToPNG();
File.WriteAllBytes(rootPath + "/" + image.name + "/" + metaData.name + ".PNG", pngData);
AssetDatabase.Refresh();
}
}
}