/// <summary> /// 图集形式为.png形式 并在unity中有很多sprite的子图 /// </summary> private void AtlasSplit() { string guidStr = Selection.assetGUIDs[0]; string path = AssetDatabase.GUIDToAssetPath(guidStr); Object[] spriteAtlas = AssetDatabase.LoadAllAssetsAtPath(path); string dirName = path.Substring(path.LastIndexOf("/") + 1).Replace(".png", ""); string targetPath = $"Assets/{dirName}"; if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); AssetDatabase.Refresh(); } for (int i = 0; i < spriteAtlas.Length; i++) { if (spriteAtlas[i] is Sprite sprite) { int spriteX = (int) sprite.rect.x; int spriteY = (int) sprite.rect.y; int spriteW = (int) sprite.rect.width; int spriteH = (int) sprite.rect.height; Texture2D texture2D = new Texture2D(spriteW, spriteH, TextureFormat.RGBA32, false); //sprite.texture 实际上是主图png的信息 所以直接在主图上取像素点 texture2D.SetPixels(sprite.texture.GetPixels(spriteX, spriteY, spriteW, spriteH)); string pngPath = $"{targetPath}/{sprite.name}.png"; using (FileStream fs = new FileStream(pngPath, FileMode.Create, FileAccess.Write)) { byte[] bytes = texture2D.EncodeToPNG(); fs.Write(bytes, 0, bytes.Length); fs.Flush(); fs.Close(); fs.Dispose(); AssetDatabase.Refresh(); } TextureImporter textureImporter = AssetImporter.GetAtPath(pngPath) as TextureImporter; PngToSprite(textureImporter); } } AssetDatabase.Refresh(); } /// <summary> /// png转成sprite /// </summary> /// <param name="textureImporter"></param> private void PngToSprite(TextureImporter textureImporter) { if (textureImporter != null && textureImporter.textureType != TextureImporterType.Sprite) { textureImporter.textureType = TextureImporterType.Sprite; textureImporter.spriteImportMode = SpriteImportMode.Single; textureImporter.spritePixelsPerUnit = 100; textureImporter.textureCompression = TextureImporterCompression.Compressed; textureImporter.SaveAndReimport(); } }
标签:fs,sprite,textureImporter,子图,int,png,string From: https://www.cnblogs.com/zjp959/p/17592782.html