NGUI 导出图集原图

作者:雨辰 发布于:2017-10-10 19:41 Tuesday 分类:Unity3D

UIAtlasMaker.cs

修改:

    void OnGUI ()
    {
        GUILayout.BeginHorizontal();
            {
                Texture tex = NGUISettings.atlas.texture;
                if (tex != null)
                {
                    if (GUILayout.Button("导出贴图(PNG)", GUILayout.Width(120f)))
                    {
                        string filePath = EditorUtility.SaveFolderPanel("保存贴图到指定文件夹", "", "");
                        ExportTexturePNGFromAtlas(filePath, NGUISettings.atlas);
                    }
                }
            }
            GUILayout.EndHorizontal();
    }
     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);
                }
            }
        }

标签: Unity3D-Editer Unity3D

发表评论:

雨辰 joyimp|@2011-2017 京ICP备16030765号