Unity3d通用工具類之NGUI圖集分解


---恢復內容開始---

Unity3d通用工具類之NGUI圖集分解

由於最近需要一些美術資源嗎,但是無奈自己不會制作UI,所以就打算去網上的項目中直接找幾張可以使用的貼圖資源。

 

但是發現這些資源已經被NGUI自帶的打包圖集工具打包好了,而且原小貼圖也已經全部刪掉了,只剩下一個預制物。

 

那么這個預制物里面包含什么呢:

1.一張大圖集貼圖

2.大貼圖的材質球

3.掛上UIAtla腳本的預制物

那么重點來了,我們該如何獲取這張大貼圖中的小貼圖呢?

 

這里我寫了個小插件,我直接在NGUI源代碼里面改:

找到NGUI的源代碼:UIAtlasMaker

在OnGUI方法里面,我新添加了可以導出貼圖的代碼:

 

            GUILayout.BeginHorizontal();
            {
                if (tex != null)
                {
                    if (GUILayout.Button("導出貼圖(PNG)",GUILayout.Width(120f)))
                    {
                        string filePath = EditorUtility.SaveFolderPanel("保存貼圖到指定文件夾","","");
                        ExportTexturePNGFromAtlas(filePath, NGUISettings.atlas);
                    }
                }
            }
            GUILayout.EndHorizontal();

ExportTexturePNGFromAtlas():

 

    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)
        {
            int xmin = Mathf.Clamp(es.x, 0, oldwith);
            int ymin = Mathf.Clamp(es.y, 0, oldHeight);
            int newWidth = Mathf.Clamp(es.width, 0, oldwith);
            int newHeight = Mathf.Clamp(es.height, 0, oldHeight);
            if (newWidth == 0 || newHeight == 0) continue;
            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);
            }
        }
    }

打開NGUI的Atlas Maker:

 點擊導出貼圖,然后會彈出選擇保存貼圖到哪個文件夾,點擊選擇文件夾之后,小貼圖就導出成功了。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM