# 这个图框了3张小图,淡蓝色进度条,钻石图标,道具背景框,其中道具背景框还设置了border。
提取出的图片
#if UNITY_EDITOR using UnityEngine; using UnityEditor; using System.IO; public static class SpriteTool { [MenuItem("Assets/提取小图")] static void ExtractSlice() { var srcTex = Selection.activeObject as Texture2D; if (null == srcTex) return; var srcTexPath = AssetDatabase.GetAssetPath(srcTex); var srcTexImporter = AssetImporter.GetAtPath(srcTexPath) as TextureImporter; if (SpriteImportMode.Multiple != srcTexImporter.spriteImportMode) { Debug.Log($"Sprite Mode不是Multiple: {srcTexPath}"); return; } var srcTexDirPath = Path.GetDirectoryName(srcTexPath); //Debug.Log($"dirPath: {srcTexDirPath}"); var outDirPath = $"{srcTexDirPath}/{srcTex.name}"; if (!Directory.Exists(outDirPath)) AssetDatabase.CreateFolder(srcTexDirPath, srcTex.name); var srcTempRT = RenderTexture.GetTemporary(srcTex.width, srcTex.height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Linear); Graphics.Blit(srcTex, srcTempRT); var oldActiveRT = RenderTexture.active; RenderTexture.active = srcTempRT; foreach (SpriteMetaData metaData in srcTexImporter.spritesheet) //遍历小图集 { var rect = metaData.rect; Debug.Log($"{srcTex.format}"); var spriteTex = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGBA32, false); Debug.Log($"{metaData.name}: rect:{metaData.rect}, border:{metaData.border}"); 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 = $"{outDirPath}/{metaData.name}.png"; File.WriteAllBytes(spriteOutPath, pngBytes); AssetDatabase.ImportAsset(spriteOutPath, ImportAssetOptions.ForceUpdate); //修改设置 var spriteTexImporter = AssetImporter.GetAtPath(spriteOutPath) as TextureImporter; if (spriteTexImporter) { spriteTexImporter.textureType = TextureImporterType.Sprite; spriteTexImporter.mipmapEnabled = false; spriteTexImporter.alphaIsTransparency = true; var setting = new TextureImporterSettings(); spriteTexImporter.ReadTextureSettings(setting); setting.spriteGenerateFallbackPhysicsShape = false; setting.spriteBorder = metaData.border; //原来的9宫格设置不能丢了 spriteTexImporter.SetTextureSettings(setting); spriteTexImporter.SaveAndReimport(); //EditorUtility.SetDirty(texImporter); } } //AssetDatabase.Refresh(); RenderTexture.active = oldActiveRT; RenderTexture.ReleaseTemporary(srcTempRT); Debug.Log("finish"); } } #endif
【参考】
Unity---制作工具导出利用SpriteEditor分割完的图片以供NGUI制作图集_Roken24的博客-CSDN博客_unity导出图片
Unity 2D切割Texture2D,图集转成单独PNG报错问题,Copy其他博主的代码实现_于毒的博客-CSDN博客
标签:RenderTexture,srcTex,导出,spriteTexImporter,图集,var,rect,metaData From: https://www.cnblogs.com/sailJs/p/16816119.html