public class TestSaveSprite
{
[MenuItem("Tools/导出精灵")]
static void SaveSprite()
{
string resourcesPath1 = "Assets/ResourcesOut/ui/atlas";
foreach (Object obj in Selection.objects)
{
string selectionPath = AssetDatabase.GetAssetPath(obj);
if (selectionPath.StartsWith(resourcesPath1))
{
string selectionExt = System.IO.Path.GetExtension(selectionPath);
if (!selectionExt.Equals(".prefab"))
{
continue;
}
UIAtlas Atlas = UnityEditor.AssetDatabase.LoadAssetAtPath<UIAtlas>(selectionPath);
string outPath = Application.dataPath + "/outSprite/" + Atlas.name;
ExportTexturePNGFromAtlas(outPath, Atlas);
AssetDatabase.Refresh();
}
}
Debug.Log("SaveSprite Finished");
}
static void ExportTexturePNGFromAtlas(string folderPath, UIAtlas atlas)
{
List<UISpriteData> exitSpritesList = atlas.spriteList;
Texture2D atlasTexture = NGUIEditorTools.ImportTexture(atlas.texture, true, false, !atlas.premultipliedAlpha);
int oldwith = atlasTexture.width;
int oldHeight = atlasTexture.height;
Color32[] oldPixels = null;
foreach (var es in exitSpritesList)
{
//限制es.x在0 ~ oldwith之间
int xmin = Mathf.Clamp(es.x, 0, oldwith);
//限制es.y在0 ~ oldHeight之间
int ymin = Mathf.Clamp(es.y, 0, oldHeight);
//限制es.width在0 ~ oldwith 之间
int newWidth = Mathf.Clamp(es.width, 0, oldwith);
//限制es.width在0 ~ oldHeight 之间
int newHeight = Mathf.Clamp(es.height, 0, oldHeight);
if (newWidth == 0 || newHeight == 0) continue;
//获取32位像素颜色列表
if (oldPixels == null) oldPixels = atlasTexture.GetPixels32();
Color32[] newPixels = new Color32[newWidth * newHeight];
for (int y = 0; y < newHeight; ++y)
{
for (int x = 0; x < newWidth; ++x)
{
int newIndex = (newHeight - 1 - y) * newWidth + x;
int oldIndex = (oldHeight - 1 - (ymin + y)) * oldwith + (xmin + x);
newPixels[newIndex] = oldPixels[oldIndex];
}
}
Texture2D t = new Texture2D(newWidth, newHeight);
t.SetPixels32(newPixels);
t.Apply();
byte[] bytes = t.EncodeToPNG();
Texture2D.DestroyImmediate(t);
t = null;
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
using (FileStream fs = new FileStream(folderPath + "/" + es.name + ".png", FileMode.CreateNew))
{
BinaryWriter writer = new BinaryWriter(fs);
writer.Write(bytes);
}
}
}
}