Sprite导出工具

发布时间 2023-07-01 01:33:01作者: yanghui01

用于导出选中的Sprite

#if UNITY_EDITOR

using System.IO;
using UnityEditor;
using UnityEngine;

public static class SpriteTool
{
    const string Output_Dir_Path = "_Temp/ExportSprite/";

    const string MenuItemPath_ExportSelectSprite = "Assets/Image/Export Select Sprite";

    [MenuItem(MenuItemPath_ExportSelectSprite, true)]
    static bool MenuItemValidator_ExportSelectSprite()
    {
        if (Application.isPlaying)
            return false;
        if (null == Selection.activeObject)
            return false;
        var sp = Selection.activeObject as Sprite;
        return null != sp;
    }


    [MenuItem(MenuItemPath_ExportSelectSprite)]
    static void MenuItem_ExportSelectSprite()
    {
        var sp = Selection.activeObject as Sprite;
        if (null == sp) return;

        if (!Directory.Exists(Output_Dir_Path) && null == Directory.CreateDirectory(Output_Dir_Path))
        {
            Debug.LogError($"{Output_Dir_Path} create fail!");
            return;
        }

        var srcTex = sp.texture;
        var srcTempRT = RenderTexture.GetTemporary(srcTex.width, srcTex.height, 0, RenderTextureFormat.Default);
        Graphics.Blit(srcTex, srcTempRT);
        var oldActiveRT = RenderTexture.active;
        RenderTexture.active = srcTempRT;

        OutputSprite(srcTempRT, sp);

        RenderTexture.active = oldActiveRT;
        RenderTexture.ReleaseTemporary(srcTempRT);

        Debug.Log("finish");
    }

    static void OutputSprite(RenderTexture srcTempRT, Sprite sp)
    {
        var rect = sp.rect;
        var spriteTex = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGBA32, false);

        var readRect = new Rect(rect.x, srcTempRT.height - (rect.y + rect.height), rect.width, rect.height); //读取是从RenderTexture, (0, 0)为左上角
        spriteTex.ReadPixels(readRect, 0, 0); //写出为Texture2D, (0, 0)为左下角
        spriteTex.Apply();

        var pngBytes = spriteTex.EncodeToPNG();
        var spriteOutPath = Path.Combine(Output_Dir_Path, $"{sp.name}.png");
        File.WriteAllBytes(spriteOutPath, pngBytes);
    }

}

#endif