切圖需求
假設有一張大的UI的圖集,我們想把它里面的小圖一張一張地切割出來,如果有plist文件,請查閱我的另一篇文章《還原TexturePacker plist 文件 切開各小圖片》
今天我們使用 Unity4.3或更高版本自帶的 Sprite Editor 來導出切片精靈
切圖效果
步驟
1、准備一張大的圖集,導入Unity的Asset/Resources/XXX/文件夾下(注意:圖集文件一定要放在Resources文件下)
2、該圖集默認是Texture,我們需要把它的Type修改成Sprite
3、接着修改Sprite Mode為Multiple,應用。然后點擊 Sprite Editor
4、在打開的Sprite Edirot 窗口中把圖集切成多個Sprite
插件代碼
5、編寫TestExportSprite.cs,放在Editor目錄下
using UnityEngine; using UnityEditor; public class TestExportSprite { [MenuItem("Assets/導出選中圖片為單獨png")] static void ExportSelSprite() { string resourcesPath = "Assets/Resources/"; foreach (Object obj in Selection.objects) { string selectionPath = AssetDatabase.GetAssetPath(obj); // 必須最上級是"Assets/Resources/" if (selectionPath.StartsWith(resourcesPath)) { string selectionExt = System.IO.Path.GetExtension(selectionPath); if (selectionExt.Length == 0) { continue; } // 得到導出路徑 string loadPath = selectionPath.Remove(selectionPath.Length - selectionExt.Length); loadPath = loadPath.Substring(resourcesPath.Length); // 加載此文件下的所有資源 Sprite[] sprites = Resources.LoadAll<Sprite>(loadPath); if (sprites.Length > 0) { // 創建導出文件夾 string outPath = Application.dataPath + "/outSprite/" + loadPath; System.IO.Directory.CreateDirectory(outPath); foreach (Sprite sprite in sprites) { // 創建單獨的紋理 Texture2D tex = new Texture2D((int)sprite.rect.width, (int)sprite.rect.height, sprite.texture.format, false); tex.SetPixels(sprite.texture.GetPixels((int)sprite.rect.xMin, (int)sprite.rect.yMin, (int)sprite.rect.width, (int)sprite.rect.height)); tex.Apply(); // 寫入成PNG文件 System.IO.File.WriteAllBytes(outPath + "/" + sprite.name + ".png", tex.EncodeToPNG()); } Debug.Log(string.Format("Export {0} to {1}",loadPath,outPath)); } } } Debug.Log("Export All Sprites Finished"); } }
5、使用Sprite Editor把圖集切割成Sprite之后,修改圖集的屬性為Advanced,並勾選 Read/Write Enabled 和Transpare
否則當你導出切片時會報錯
UnityException: Texture 'UIAtlas' is not readable, the texture memory can not be accessed from scripts. You can make the texture readable in the Texture Import Settings. UnityEngine.Texture2D.GetPixels (Int32 x, Int32 y, Int32 blockWidth, Int32 blockHeight) (at C:/BuildAgent/work/aeedb04a1292f85a/artifacts/EditorGenerated/TextureBindings.cs:259) TestSaveSprite.SaveSprite () (at Assets/Editor/TestSaveSprite.cs:39)
5、在Resources目錄下選中UIAtlas.psd,右鍵,選擇“導出選中圖片為單獨png
說明
部分內容參考自:http://blog.csdn.net/akof1314/article/details/38845933