Atlas maker lets you create atlases from a bunch of small textures. It's an alternative to using the external Texture Packer.
Inheritance: EditorWindow
コード例 #1
0
    /// <summary>
    /// Add a dark shadowy outline around the sprite, giving it some visual depth.
    /// </summary>

    void AddOutline(UISpriteData sprite)
    {
        List <UIAtlasMaker.SpriteEntry> sprites = new List <UIAtlasMaker.SpriteEntry>();

        UIAtlasMaker.ExtractSprites(mAtlas, sprites);
        UIAtlasMaker.SpriteEntry se = null;

        for (int i = 0; i < sprites.Count; ++i)
        {
            if (sprites[i].name == sprite.name)
            {
                se = sprites[i];
                break;
            }
        }

        if (se != null)
        {
            int w1 = se.tex.width;
            int h1 = se.tex.height;

            int w2 = w1 + 2;
            int h2 = h1 + 2;

            Color32[] c2 = NGUIEditorTools.AddBorder(se.tex.GetPixels32(), w1, h1);
            NGUIEditorTools.AddDepth(c2, w2, h2, NGUISettings.backgroundColor);

            if (se.temporaryTexture)
            {
                DestroyImmediate(se.tex);
            }

            if ((se.borderLeft | se.borderRight | se.borderBottom | se.borderTop) != 0)
            {
                ++se.borderLeft;
                ++se.borderRight;
                ++se.borderTop;
                ++se.borderBottom;
            }

            se.tex      = new Texture2D(w2, h2);
            se.tex.name = sprite.name;
            se.tex.SetPixels32(c2);
            se.tex.Apply();
            se.temporaryTexture = true;

            UIAtlasMaker.UpdateAtlas(mAtlas, sprites);

            DestroyImmediate(se.tex);
            se.tex = null;
        }
    }
コード例 #2
0
ファイル: PsdWidgeteer.cs プロジェクト: wonghungwing/FastGUI
    // AdjustPosition
    #endregion

    #region AddTexture2DToAtlas

    /// <summary>
    /// Adds a texture to the atlas, the sprite data
    /// </summary>
    /// <param name="texture"></param>
    /// <returns></returns>
    private static UISpriteData AddTexture2DToAtlas(Texture2D texture)
    {
        UIAtlasMaker.AddOrUpdate(NGUISettings.atlas, texture);

        // NGUI v3 now shows its own progress panel, so we have to clear it when it finishes
        EditorUtility.ClearProgressBar();

        // now re-show our progress bar
        PsdImporter.UpdateProgress(false);

        // return the sprite
        return(NGUISettings.atlas.GetSprite(texture.name));
    }
コード例 #3
0
    /// <summary>
    /// Add a transparent border around the sprite.
    /// </summary>

    void AddTransparentBorder(UISpriteData sprite)
    {
        List <UIAtlasMaker.SpriteEntry> sprites = new List <UIAtlasMaker.SpriteEntry>();

        UIAtlasMaker.ExtractSprites(mAtlas, sprites);
        UIAtlasMaker.SpriteEntry se = null;

        for (int i = 0; i < sprites.Count; ++i)
        {
            if (sprites[i].name == sprite.name)
            {
                se = sprites[i];
                break;
            }
        }

        if (se != null)
        {
            int w1 = se.tex.width;
            int h1 = se.tex.height;

            int w2 = w1 + 2;
            int h2 = h1 + 2;

            var c2 = NGUIEditorTools.AddBorder(se.tex.GetPixels32(), w1, h1);

            if (se.temporaryTexture)
            {
                DestroyImmediate(se.tex);
            }

            ++se.borderLeft;
            ++se.borderRight;
            ++se.borderTop;
            ++se.borderBottom;

            se.tex      = new Texture2D(w2, h2);
            se.tex.name = sprite.name;
            se.tex.SetPixels32(c2);
            se.tex.Apply();
            se.temporaryTexture = true;

            var before = NGUISettings.atlasTrimming;
            NGUISettings.atlasTrimming = false;
            UIAtlasMaker.UpdateAtlas(mAtlas, sprites);
            NGUISettings.atlasTrimming = before;

            DestroyImmediate(se.tex);
            se.tex = null;
        }
    }
コード例 #4
0
    /// <summary>
    /// Delete the sprite (context menu selection)
    /// </summary>
    void DeleteSprite(object obj)
    {
        if (this == null) return;
        UISpriteData sd = obj as UISpriteData;

        List<UIAtlasMaker.SpriteEntry> sprites = new List<UIAtlasMaker.SpriteEntry>();
        UIAtlasMaker.ExtractSprites(NGUISettings.atlas, sprites);

        for (int i = sprites.Count; i > 0; )
        {
            UIAtlasMaker.SpriteEntry ent = sprites[--i];
            if (ent.name == sd.name)
                sprites.RemoveAt(i);
        }
        UIAtlasMaker.UpdateAtlas(NGUISettings.atlas, sprites);
        NGUIEditorTools.RepaintSprites();
    }
コード例 #5
0
    private void AddOrUpdate(UIAtlas atlas, List <SpriteEntry> sprites)
    {
        if (sprites.Count > 0)
        {
            // Combine all sprites into a single texture and save it
            if (UIAtlasMaker.UpdateTexture(atlas, sprites))
            {
                // Replace the sprites within the atlas
                UIAtlasMaker.ReplaceSprites(atlas, sprites);
            }

            // Release the temporary textures
            UIAtlasMaker.ReleaseSprites(sprites);
            EditorUtility.ClearProgressBar();
            return;
        }
    }
コード例 #6
0
ファイル: AtlasExtract.cs プロジェクト: profiles/Fish
    private static void ExtractSprite(UIAtlas mAtlas, string mDirectory)
    {
        Debug.Log("Generate " + mAtlas.name);

        string rootPath = mDirectory;

        if (!Directory.Exists(rootPath + "/AllUI"))
        {
            Directory.CreateDirectory(rootPath + "/AllUI");
        }
        rootPath = mDirectory + "/AllUI";

        if (!string.IsNullOrEmpty(rootPath))
        {
            if (!Directory.Exists(rootPath + "/" + mAtlas.name))//判断文件夹是否存在
            {
                Directory.CreateDirectory(rootPath + "/" + mAtlas.name);
            }
            else
            {
                Debug.LogError("Same Atlas Name!" + mAtlas.name);
                return;
                //Directory.CreateDirectory(rootPath + "/" + mAtlas.name + "1");
            }

            string folderPath = rootPath + "/" + mAtlas.name;

            foreach (UISpriteData mSpriteData in mAtlas.spriteList)
            {
                UIAtlasMaker.SpriteEntry spriteEntry = UIAtlasMaker.ExtractSprite(mAtlas, mSpriteData.name);
                string spritePath = folderPath + "/" + mSpriteData.name + ".png";

                if (spriteEntry != null)
                {
                    byte[] bytes = spriteEntry.tex.EncodeToPNG();
                    File.WriteAllBytes(spritePath, bytes);
                    AssetDatabase.ImportAsset(spritePath);
                    if (spriteEntry.temporaryTexture)
                    {
                        DestroyImmediate(spriteEntry.tex);
                    }
                }
            }
        }
    }
コード例 #7
0
    static List <Texture2D> SpliteTexture(UIAtlas atlas, float scaling, out Texture2D tex, List <UISpriteData> splist)
    {
        List <Texture2D> texList = new List <Texture2D>();
        List <UIAtlasMaker.SpriteEntry> entryList = new List <UIAtlasMaker.SpriteEntry>();

        UIAtlasMaker.ExtractSprites(atlas, entryList);
        int ij = 0;

        foreach (UIAtlasMaker.SpriteEntry sd in entryList)
        {
            //Debug.Log(sd.paddingBottom + "," + sd.paddingLeft + "," + sd.paddingRight + "," + sd.paddingTop);
            //byte[] att = sd.tex.EncodeToPNG();
            //FileStream fs = new FileStream(Application.dataPath + "/Resources/vata"+ ij +".png", FileMode.Create);
            //fs.Write(att, 0, att.Length);
            //fs.Close();
            texList.Add(sd.tex);
            ++ij;
        }
        {
            const int SIZE = 380;
            tex = new Texture2D(SIZE, SIZE, TextureFormat.ARGB32, false);
            Rect[] rectList = tex.PackTextures(texList.ToArray(), 2, tex.width);
            int    i        = 0;
            foreach (Rect r in rectList)
            {
                UISpriteData sd        = new UISpriteData();
                Rect         finalRect = NGUIMath.ConvertToPixels(r, tex.width, tex.height, true);
                sd.x      = Mathf.RoundToInt(finalRect.x);
                sd.y      = Mathf.RoundToInt(finalRect.y);
                sd.width  = Mathf.RoundToInt(finalRect.width);
                sd.height = Mathf.RoundToInt(finalRect.height);

                sd.name = entryList[i++].name;
                Debug.Log("sprite:" + sd.name + ": " + finalRect.x + "," + finalRect.y + "," + finalRect.width + "," + finalRect.height);
                splist.Add(sd);
            }
            byte[]     att = tex.EncodeToPNG();
            FileStream fs  = new FileStream(Application.dataPath + "/Resources/vata.png", FileMode.Create);
            fs.Write(att, 0, att.Length);
            fs.Close();
        }
        EditorUtility.ClearProgressBar();
        return(texList);
    }
コード例 #8
0
    void DeleteSprite(SpriteInfo info)
    {
        if (this == null)
        {
            return;
        }
        List <UIAtlasMaker.SpriteEntry> sprites = new List <UIAtlasMaker.SpriteEntry>();

        UIAtlasMaker.ExtractSprites(info.Atlas, sprites);

        for (int i = sprites.Count; i > 0;)
        {
            UIAtlasMaker.SpriteEntry ent = sprites[--i];
            if (ent.name == info.Data.name)
            {
                sprites.RemoveAt(i);
            }
        }
        UIAtlasMaker.UpdateAtlas(info.Atlas, sprites);
        NGUIEditorTools.RepaintSprites();
    }
コード例 #9
0
    static private void UpdateUIAtlas(UIAtlas atlas, List <UIAtlasMaker.SpriteEntry> sprites, out Texture2D atlasTex)
    {
        atlasTex = null;
        if (
            (null == atlas) ||
            (null == sprites) ||
            (0 == sprites.Count)
            )
        {
            return;
        }

        if (UpdateTexture(atlas, sprites, out atlasTex))
        {
            UIAtlasMaker.ReplaceSprites(atlas, sprites);
        }

        UIAtlasMaker.ReleaseSprites(sprites);

        atlas.MarkAsChanged();
    }
コード例 #10
0
 private void Update()
 {
     if (!beginPack)
     {
         return;
     }
     if (j >= 0)
     {
         j--; return;
     }
     if (atlas != null && atlas.Length > i)
     {
         UnityEngine.Object o = atlas[i];
         if (atlasInfoDic.ContainsKey(o))
         {
             if (atlasInfoDic[o].select)
             {
                 NGUISettings.unityPacking     = atlasInfoDic[o].unityPacking;
                 NGUISettings.forceSquareAtlas = atlasInfoDic[o].forceSquareAtlas;
                 UIAtlasMaker.OneKeyPack(atlas[i]);
                 i++;
                 j = 20;
             }
             else
             {
                 i++;
             }
         }
     }
     else
     {
         Debug.LogError("一键打包图集完成");
         Close();
         beginPack = false;
         NGUISettings.unityPacking     = true;
         NGUISettings.forceSquareAtlas = false;
         return;
     }
 }
コード例 #11
0
	/// <summary>
	/// Duplicate the specified sprite.
	/// </summary>

	static public SpriteEntry DuplicateSprite (UIAtlas atlas, string spriteName)
	{
		if (atlas == null || atlas.texture == null) return null;
		UISpriteData sd = atlas.GetSprite(spriteName);
		if (sd == null) return null;

		Texture2D tex = NGUIEditorTools.ImportTexture(atlas.texture, true, true, false);
		SpriteEntry se = ExtractSprite(sd, tex);

		if (se != null)
		{
			se.name = se.name + " (Copy)";

			List<UIAtlasMaker.SpriteEntry> sprites = new List<UIAtlasMaker.SpriteEntry>();
			UIAtlasMaker.ExtractSprites(atlas, sprites);
			sprites.Add(se);
			UIAtlasMaker.UpdateAtlas(atlas, sprites);
			se.Release();
		}
		else NGUIEditorTools.ImportTexture(atlas.texture, false, false, !atlas.premultipliedAlpha);
		return se;
	}
コード例 #12
0
	void OnDisable () { instance = null; }
コード例 #13
0
	void OnEnable () { instance = this; }
コード例 #14
0
    /// <summary>
    /// Add a dark shadowy outline around the sprite, giving it some visual depth.
    /// </summary>

    void AddDepth(UISpriteData sprite)
    {
        List <UIAtlasMaker.SpriteEntry> sprites = new List <UIAtlasMaker.SpriteEntry>();

        UIAtlasMaker.ExtractSprites(mAtlas, sprites);
        UIAtlasMaker.SpriteEntry se = null;

        for (int i = 0; i < sprites.Count; ++i)
        {
            if (sprites[i].name == sprite.name)
            {
                se = sprites[i];
                break;
            }
        }

        if (se != null)
        {
            int w1 = se.tex.width;
            int h1 = se.tex.height;

            int w2 = w1 + 2;
            int h2 = h1 + 2;

            Color32[] c1 = se.tex.GetPixels32();
            Color32[] c2 = new Color32[w2 * h2];

            for (int y2 = 0; y2 < h2; ++y2)
            {
                int y1 = NGUIMath.ClampIndex(y2 - 1, h1);

                for (int x2 = 0; x2 < w2; ++x2)
                {
                    int x1 = NGUIMath.ClampIndex(x2 - 1, w1);
                    int i2 = x2 + y2 * w2;
                    c2[i2] = c1[x1 + y1 * w1];

                    if (x2 == 0 || x2 + 1 == w2 || y2 == 0 || y2 + 1 == h2)
                    {
                        c2[i2].a = 0;
                    }
                }
            }

            for (int y2 = 0; y2 < h2; ++y2)
            {
                for (int x2 = 0; x2 < w2; ++x2)
                {
                    int     index = x2 + y2 * w2;
                    Color32 uc    = c2[index];
                    if (uc.a == 255)
                    {
                        continue;
                    }

                    Color original = uc;
                    float val      = original.a * 4f;
                    int   count    = 4;
                    float div1     = 1f / 255f;
                    float div2     = 2f / 255f;

                    if (x2 != 0)
                    {
                        val   += c2[x2 - 1 + y2 * w2].a * div2;
                        count += 2;
                    }

                    if (x2 + 1 != w2)
                    {
                        val   += c2[x2 + 1 + y2 * w2].a * div2;
                        count += 2;
                    }

                    if (y2 != 0)
                    {
                        val   += c2[x2 + (y2 - 1) * w2].a * div2;
                        count += 2;
                    }

                    if (y2 + 1 != h2)
                    {
                        val   += c2[x2 + (y2 + 1) * w2].a * div2;
                        count += 2;
                    }

                    if (x2 != 0 && y2 != 0)
                    {
                        val += c2[x2 - 1 + (y2 - 1) * w2].a * div1;
                        ++count;
                    }

                    if (x2 != 0 && y2 + 1 != h2)
                    {
                        val += c2[x2 - 1 + (y2 + 1) * w2].a * div1;
                        ++count;
                    }

                    if (x2 + 1 != w2 && y2 != 0)
                    {
                        val += c2[x2 + 1 + (y2 - 1) * w2].a * div1;
                        ++count;
                    }

                    if (x2 + 1 != w2 && y2 + 1 != h2)
                    {
                        val += c2[x2 + 1 + (y2 + 1) * w2].a * div1;
                        ++count;
                    }

                    val /= count;

                    Color shadow = new Color(0f, 0f, 0f, val);
                    shadow    = Color.Lerp(original, shadow, mAlpha);
                    c2[index] = Color.Lerp(shadow, original, original.a);
                }
            }

            if (se.temporaryTexture)
            {
                DestroyImmediate(se.tex);
            }

            ++se.borderLeft;
            ++se.borderRight;
            ++se.borderTop;
            ++se.borderBottom;

            se.tex      = new Texture2D(w2, h2);
            se.tex.name = sprite.name;
            se.tex.SetPixels32(c2);
            se.tex.Apply();
            se.temporaryTexture = true;

            UIAtlasMaker.UpdateAtlas(mAtlas, sprites);

            DestroyImmediate(se.tex);
            se.tex = null;
        }
    }
コード例 #15
0
    /// <summary>
    /// Add a transparent border around the sprite.
    /// </summary>

    void AddTransparentBorder(UISpriteData sprite)
    {
        List <UIAtlasMaker.SpriteEntry> sprites = new List <UIAtlasMaker.SpriteEntry>();

        UIAtlasMaker.ExtractSprites(mAtlas, sprites);
        UIAtlasMaker.SpriteEntry se = null;

        for (int i = 0; i < sprites.Count; ++i)
        {
            if (sprites[i].name == sprite.name)
            {
                se = sprites[i];
                break;
            }
        }

        if (se != null)
        {
            int w1 = se.tex.width;
            int h1 = se.tex.height;

            int w2 = w1 + 2;
            int h2 = h1 + 2;

            Color32[] c1 = se.tex.GetPixels32();
            Color32[] c2 = new Color32[w2 * h2];

            for (int y2 = 0; y2 < h2; ++y2)
            {
                int y1 = NGUIMath.ClampIndex(y2 - 1, h1);

                for (int x2 = 0; x2 < w2; ++x2)
                {
                    int x1 = NGUIMath.ClampIndex(x2 - 1, w1);
                    int i2 = x2 + y2 * w2;
                    c2[i2] = c1[x1 + y1 * w1];

                    if (x2 == 0 || x2 + 1 == w2 || y2 == 0 || y2 + 1 == h2)
                    {
                        c2[i2].a = 0;
                    }
                }
            }

            if (se.temporaryTexture)
            {
                DestroyImmediate(se.tex);
            }

            ++se.borderLeft;
            ++se.borderRight;
            ++se.borderTop;
            ++se.borderBottom;

            se.tex      = new Texture2D(w2, h2);
            se.tex.name = sprite.name;
            se.tex.SetPixels32(c2);
            se.tex.Apply();
            se.temporaryTexture = true;

            UIAtlasMaker.UpdateAtlas(mAtlas, sprites);

            DestroyImmediate(se.tex);
            se.tex = null;
        }
    }
コード例 #16
0
    /// <summary>
    /// Crop the border pixels around the sprite.
    /// </summary>

    void CropBorder(UISpriteData sprite)
    {
        var sprites = new List <UIAtlasMaker.SpriteEntry>();

        UIAtlasMaker.ExtractSprites(mAtlas, sprites);
        UIAtlasMaker.SpriteEntry se = null;

        for (int i = 0; i < sprites.Count; ++i)
        {
            if (sprites[i].name == sprite.name)
            {
                se = sprites[i];
                break;
            }
        }

        if (se != null)
        {
            int w1 = se.tex.width;
            int h1 = se.tex.height;

            int w2 = w1 - se.borderLeft - se.borderRight;
            int h2 = h1 - se.borderTop - se.borderBottom;

            var c1 = se.tex.GetPixels32();
            var c2 = new Color32[w2 * h2];

            for (int y2 = 0; y2 < h2; ++y2)
            {
                int y1 = y2 + se.borderBottom;

                for (int x2 = 0; x2 < w2; ++x2)
                {
                    int x1 = x2 + se.borderLeft;
                    c2[x2 + y2 * w2] = c1[x1 + y1 * w1];
                }
            }

            se.borderLeft   = 0;
            se.borderRight  = 0;
            se.borderTop    = 0;
            se.borderBottom = 0;

            if (se.temporaryTexture)
            {
                DestroyImmediate(se.tex);
            }

            se.tex      = new Texture2D(w2, h2);
            se.tex.name = sprite.name;
            se.tex.SetPixels32(c2);
            se.tex.Apply();
            se.temporaryTexture = true;

            var before = NGUISettings.atlasTrimming;
            NGUISettings.atlasTrimming = false;
            UIAtlasMaker.UpdateAtlas(mAtlas, sprites);
            NGUISettings.atlasTrimming = before;

            DestroyImmediate(se.tex);
            se.tex = null;
        }
    }
コード例 #17
0
ファイル: UIAtlasMaker.cs プロジェクト: willFuRoy/Unity
 void OnEnable()
 {
     instance = this;
 }
コード例 #18
0
    static void ExportAtlasToPng()
    {
        string RootFolderPath = EditorUtility.SaveFolderPanel("Save As", "Assets", "atlas");

        //获取被选中的游戏对象
        Object[] SelectedAsset = Selection.GetFiltered(typeof(UIAtlas), SelectionMode.Unfiltered);

        foreach (Object obj in SelectedAsset)
        {
            UIAtlas atlas = obj as UIAtlas;
            if (atlas == null)
            {
                continue;
            }

            string folderPath = RootFolderPath + "/" + atlas.name;
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            for (int i = 0; i < atlas.spriteList.Count; i++)
            {
                UISpriteData sprite = atlas.spriteList[i];

                string path = folderPath + "/" + sprite.name + ".png";

                //NGUISettings.currentPath = System.IO.Path.GetDirectoryName(path);
                int width  = sprite.width + sprite.paddingLeft + sprite.paddingRight;
                int height = sprite.height + sprite.paddingTop + sprite.paddingBottom;

                UIAtlasMaker.SpriteEntry se = UIAtlasMaker.ExtractSprite(atlas, sprite.name);

                if (se != null)
                {
                    byte[] bytes = null;

                    if (sprite.hasPadding)
                    {
                        //创建图片原尺寸,使用透明填充
                        Texture2D tex        = new Texture2D(width, height, TextureFormat.ARGB32, false);
                        int       count      = width * height;
                        Color[]   alphaColor = new Color[width * height];
                        for (int j = 0; j < count; j++)
                        {
                            alphaColor[j] = new Color(0, 0, 0, 0);
                        }

                        tex.SetPixels(alphaColor);
                        tex.SetPixels(sprite.paddingLeft, sprite.paddingTop, se.tex.width, se.tex.height, se.tex.GetPixels());
                        bytes = tex.EncodeToPNG();
                    }
                    else
                    {
                        //没有空白的,不需要重新创建图片透明填充,以方便导出时速度更快
                        bytes = se.tex.EncodeToPNG();
                    }

                    File.WriteAllBytes(path, bytes);
                    AssetDatabase.ImportAsset(path);
                    if (se.temporaryTexture)
                    {
                        GameObject.DestroyImmediate(se.tex);
                    }
                }

                Debug.Log(string.Format("export: atlas={0} sprite={1} {2}/{3}", atlas.name, sprite, i + 1, atlas.spriteList.Count));
            }
        }

        AssetDatabase.Refresh();
        EditorUtility.DisplayDialog("Packager", "Succeed!", "ok");
    }
コード例 #19
0
    private bool DrawAdvancedMenu()
    {
        if (Application.isPlaying == true)
        {
            return(true);
        }

        if (NGUIEditorTools.DrawHeader("Advanced menu") == false)
        {
            return(true);
        }

        NGUIEditorTools.BeginContents();
        GUILayout.BeginVertical();

        GUILayout.BeginHorizontal();
        _texToSprite = EditorGUILayout.ObjectField(_texToSprite, typeof(Texture), false) as Texture;

        if (GUILayout.Button("Add", GUILayout.Width(40f)))
        {
            if (_texToSprite == null)
            {
                Debug.LogError("Select a texture first.");
                return(false);
            }

            UIAtlas curAtlas = GetAtlas();

            if (curAtlas == null)
            {
                if (CreateOwnAtlas() == false)
                {
                    return(false);
                }

                curAtlas = GetAtlas();
            }

            List <UIAtlasMaker.SpriteEntry> entries = UIAtlasMaker.CreateSprites(new List <Texture>()
            {
                _texToSprite
            });
            UIAtlasMaker.ExtractSprites(curAtlas, entries);
            UIAtlasMaker.UpdateAtlas(curAtlas, entries);

            SelectSprite(_texToSprite.name);

            return(false);
        }

        if (GUILayout.Button("New") == true)
        {
            if (_texToSprite == null)
            {
                Debug.LogError("Select a texture first.");
                return(false);
            }

            if (CreateOwnAtlas() == false)
            {
                return(false);
            }

            UIAtlas curAtlas = GetAtlas();

            List <UIAtlasMaker.SpriteEntry> entries = UIAtlasMaker.CreateSprites(new List <Texture>()
            {
                _texToSprite
            });
            UIAtlasMaker.ExtractSprites(curAtlas, entries);
            UIAtlasMaker.UpdateAtlas(curAtlas, entries);

            SelectSprite(_texToSprite.name);

            return(false);
        }

        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        if (GUILayout.Button("Delete sprite") == true)
        {
            UIAtlas curAtlas   = GetAtlas();
            string  curSprName = GetSpriteName();

            if (curAtlas == null)
            {
                Debug.LogError("No atlas in this UISprite");
                return(false);
            }

            if (string.IsNullOrEmpty(curSprName) == true)
            {
                Debug.LogError("No sprite in this UISprite");
                return(false);
            }

            List <UIAtlasMaker.SpriteEntry> lstSprites = new List <UIAtlasMaker.SpriteEntry>();
            UIAtlasMaker.ExtractSprites(curAtlas, lstSprites);

            for (int i = lstSprites.Count; i > 0;)
            {
                UIAtlasMaker.SpriteEntry entry = lstSprites[--i];

                if (entry.name == curSprName)
                {
                    lstSprites.RemoveAt(i);
                }
            }
            UIAtlasMaker.UpdateAtlas(curAtlas, lstSprites);
            NGUIEditorTools.RepaintSprites();

            return(false);
        }

        if (GUILayout.Button("Atlas Maker") == true)
        {
            EditorWindow.GetWindow <UIAtlasMaker>(false, "Atlas Maker", true).Show();

            return(false);
        }

        GUILayout.EndHorizontal();

        GUILayout.EndVertical();
        NGUIEditorTools.EndContents();

        return(true);
    }
コード例 #20
0
    public static UIAtlas CreateAtlas(string atlasName, Device device, AtlasType atlasType)
    {
        List <UISpriteData> oldSpriteData;

#if RSATLASHELPER_DEBUG
        Debug.Log(string.Format("AddNewAtlas; atlasName = {0}, device = {1}, atlasType = {2}", atlasName, device, atlasType));
#endif

        string texturesDir = GetAtlasTexturesDirectory(atlasName, device, atlasType);

        DirectoryInfo dirInfo = new DirectoryInfo("Assets/" + texturesDir);
        if (dirInfo == null || !dirInfo.Exists)
        {
            Debug.LogWarning("Directory does not exist; " + atlasName + ", for device: " + device + " " + texturesDir);
            return(null);
        }
        List <FileInfo> fis;
        GetTextureAssets(dirInfo, out fis);

        if (fis == null && fis.Count == 0)
        {
            Debug.LogWarning("Directory empty; " + atlasName + ", for device: " + device);
            return(null);
        }

        UIAtlas newAtlas = CreateAtlasInternal(atlasName, device, atlasType, out oldSpriteData);
        if (newAtlas == null)
        {
            Debug.LogWarning("Could not create atlas for " + atlasName + ", device = " + device);
            return(null);
        }

        NGUISettings.atlas            = newAtlas;
        NGUISettings.atlasPadding     = 2;
        NGUISettings.atlasTrimming    = false;
        NGUISettings.forceSquareAtlas = true;
        NGUISettings.allow4096        = (atlasType == AtlasType.HD);
        NGUISettings.fontTexture      = null;
        NGUISettings.unityPacking     = false;

        if (device == Device.Tablet || device == Device.Standalone)
        {
            newAtlas.pixelSize = (atlasType == AtlasType.HD) ? 1f : 2f;
        }
        else
        {
            newAtlas.pixelSize = 1f;
        }

        EditorUtility.SetDirty(newAtlas.gameObject);

        List <Texture> textures = new List <Texture>();

        foreach (FileInfo fi in fis)
        {
            string textureName = "Assets" + texturesDir + fi.Name;

            Texture2D tex = AssetDatabase.LoadAssetAtPath(textureName, typeof(Texture2D)) as Texture2D;

            TextureImporter texImporter = AssetImporter.GetAtPath(textureName) as TextureImporter;
            texImporter.textureType         = TextureImporterType.Default;
            texImporter.npotScale           = TextureImporterNPOTScale.None;
            texImporter.generateCubemap     = TextureImporterGenerateCubemap.None;
            texImporter.normalmap           = false;
            texImporter.linearTexture       = true;
            texImporter.alphaIsTransparency = true;
            texImporter.convertToNormalmap  = false;
            texImporter.grayscaleToAlpha    = false;
            texImporter.lightmap            = false;
            texImporter.npotScale           = TextureImporterNPOTScale.None;
            texImporter.filterMode          = FilterMode.Point;
            texImporter.wrapMode            = TextureWrapMode.Clamp;
            texImporter.maxTextureSize      = 4096;
            texImporter.mipmapEnabled       = false;
            texImporter.textureFormat       = TextureImporterFormat.AutomaticTruecolor;
            AssetDatabase.ImportAsset(textureName, ImportAssetOptions.ForceUpdate);

            tex.filterMode = FilterMode.Bilinear;
            tex.wrapMode   = TextureWrapMode.Clamp;

            textures.Add(tex);

#if RSATLASHELPER_DEBUG
            Debug.Log("- added tex: " + textureName);
#endif
        }

        List <UIAtlasMaker.SpriteEntry> sprites = UIAtlasMaker.CreateSprites(textures);
        UIAtlasMaker.ExtractSprites(newAtlas, sprites);
        UIAtlasMaker.UpdateAtlas(newAtlas, sprites);
        AssetDatabase.SaveAssets();

        {
            string resourceDir = GetAtlasResourceFolder(device, atlasType);
            string atlasName2  = GetAtlasName(atlasName, device, atlasType);
            string newTex      = "Assets" + resourceDir + atlasName2 + ".png";

            TextureImporter texImporter    = AssetImporter.GetAtPath(newTex) as TextureImporter;
            int             maxTextureSize = atlasType == AtlasType.HD ? 4096 : 2048;
            texImporter.maxTextureSize = maxTextureSize;
            texImporter.textureFormat  = TextureImporterFormat.AutomaticCompressed;
            if (device == Device.Phone)
            {
                texImporter.mipmapEnabled = true;
                texImporter.borderMipmap  = true;
                texImporter.mipmapFilter  = TextureImporterMipFilter.BoxFilter;
            }
            else
            {
                texImporter.mipmapEnabled = false;
            }
            texImporter.alphaIsTransparency = true;
            texImporter.filterMode          = FilterMode.Bilinear;
            texImporter.wrapMode            = TextureWrapMode.Clamp;
            texImporter.anisoLevel          = 1;
            texImporter.SetPlatformTextureSettings("iPhone", maxTextureSize, TextureImporterFormat.PVRTC_RGBA4);
            texImporter.SetPlatformTextureSettings("Android", maxTextureSize, TextureImporterFormat.PVRTC_RGBA4);
            AssetDatabase.ImportAsset(newTex, ImportAssetOptions.ForceUpdate);
        }

        UpdateAtlasSpriteData(ref newAtlas, ref oldSpriteData);

#if RSATLASHELPER_DEBUG
        DebugAtlasSpriteData(ref newAtlas);
#endif

        newAtlas.MarkAsChanged();
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

        return(newAtlas);
    }
コード例 #21
0
    /// <summary>
    /// Draw the inspector widget.
    /// </summary>

    public override void OnInspectorGUI()
    {
        NGUIEditorTools.SetLabelWidth(80f);

        if (mAtlas == null)
        {
            EditorGUILayout.HelpBox("Invalid asset. Please re-create it.", MessageType.Error, true);
            return;
        }

        UISpriteData sprite = (mAtlas != null) ? mAtlas.GetSprite(NGUISettings.selectedSprite) : null;

        GUILayout.Space(6f);

        if (mAtlas.replacement != null)
        {
            mType        = AtlasType.Reference;
            mReplacement = mAtlas.replacement;
        }

        GUILayout.BeginHorizontal();
        AtlasType after = (AtlasType)EditorGUILayout.EnumPopup("Atlas Type", mType);

        NGUIEditorTools.DrawPadding();
        GUILayout.EndHorizontal();

        if (mType != after)
        {
            if (after == AtlasType.Normal)
            {
                mType = AtlasType.Normal;
                OnSelectAtlas(null);
            }
            else
            {
                mType = AtlasType.Reference;
            }
        }

        if (mType == AtlasType.Reference)
        {
            ComponentSelector.Draw(mAtlas.replacement, OnSelectAtlas, true);

            GUILayout.Space(6f);
            EditorGUILayout.HelpBox("You can have one atlas simply point to " +
                                    "another one. This is useful if you want to be " +
                                    "able to quickly replace the contents of one " +
                                    "atlas with another one, for example for " +
                                    "swapping an SD atlas with an HD one, or " +
                                    "replacing an English atlas with a Chinese " +
                                    "one. All the sprites referencing this atlas " +
                                    "will update their references to the new one.", MessageType.Info);

            if (mReplacement != (mAtlas as INGUIAtlas) && mAtlas.replacement != mReplacement)
            {
                NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas as Object);
                mAtlas.replacement = mReplacement;
                NGUITools.SetDirty(mAtlas as Object);
            }
            return;
        }

        if (mAtlas is UIAtlas)
        {
            EditorGUILayout.HelpBox("Legacy atlas type should be upgraded in order to maintain compatibility with Unity 2018 and newer.", MessageType.Warning, true);

            if (GUILayout.Button("Upgrade"))
            {
                var path = EditorUtility.SaveFilePanelInProject("Save As", (mAtlas as Object).name + ".asset", "asset", "Save atlas as...", NGUISettings.currentPath);

                if (!string.IsNullOrEmpty(path))
                {
                    NGUISettings.currentPath = System.IO.Path.GetDirectoryName(path);
                    var asset = ScriptableObject.CreateInstance <NGUIAtlas>();
                    asset.spriteList     = mAtlas.spriteList;
                    asset.spriteMaterial = mAtlas.spriteMaterial;

                    var atlasName = path.Replace(".asset", "");
                    atlasName  = atlasName.Substring(path.LastIndexOfAny(new char[] { '/', '\\' }) + 1);
                    asset.name = atlasName;

                    var existing = AssetDatabase.LoadMainAssetAtPath(path);
                    if (existing != null)
                    {
                        EditorUtility.CopySerialized(asset, existing);
                    }
                    else
                    {
                        AssetDatabase.CreateAsset(asset, path);
                    }

                    AssetDatabase.SaveAssets();
                    AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

                    asset = AssetDatabase.LoadAssetAtPath <NGUIAtlas>(path);
                    NGUISettings.atlas     = asset;
                    Selection.activeObject = NGUISettings.atlas as Object;

                    if (asset != null)
                    {
                        mAtlas.replacement = asset;
                        mAtlas.MarkAsChanged();
                    }
                }
            }
        }

        //GUILayout.Space(6f);
        Material mat = EditorGUILayout.ObjectField("Material", mAtlas.spriteMaterial, typeof(Material), false) as Material;

        if (mAtlas.spriteMaterial != mat)
        {
            NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas as Object);
            mAtlas.spriteMaterial = mat;

            // Ensure that this atlas has valid import settings
            if (mAtlas.texture != null)
            {
                NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
            }

            mAtlas.MarkAsChanged();
        }

        if (mat != null)
        {
            TextAsset ta = EditorGUILayout.ObjectField("TP Import", null, typeof(TextAsset), false) as TextAsset;

            if (ta != null)
            {
                // Ensure that this atlas has valid import settings
                if (mAtlas.texture != null)
                {
                    NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
                }

                NGUIEditorTools.RegisterUndo("Import Sprites", mAtlas as Object);
                NGUIJson.LoadSpriteData(mAtlas, ta);
                if (sprite != null)
                {
                    sprite = mAtlas.GetSprite(sprite.name);
                }
                mAtlas.MarkAsChanged();
            }

            float pixelSize = EditorGUILayout.FloatField("Pixel Size", mAtlas.pixelSize, GUILayout.Width(120f));

            if (pixelSize != mAtlas.pixelSize)
            {
                NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas as Object);
                mAtlas.pixelSize = pixelSize;
            }
        }

        if (mAtlas.spriteMaterial != null)
        {
            Color blueColor  = new Color(0f, 0.7f, 1f, 1f);
            Color greenColor = new Color(0.4f, 1f, 0f, 1f);

            if (sprite == null && mAtlas.spriteList.Count > 0)
            {
                string spriteName = NGUISettings.selectedSprite;
                if (!string.IsNullOrEmpty(spriteName))
                {
                    sprite = mAtlas.GetSprite(spriteName);
                }
                if (sprite == null)
                {
                    sprite = mAtlas.spriteList[0];
                }
            }

            if (sprite != null)
            {
                if (sprite == null)
                {
                    return;
                }

                Texture2D tex = mAtlas.spriteMaterial.mainTexture as Texture2D;

                if (tex != null)
                {
                    if (!NGUIEditorTools.DrawHeader("Sprite Details"))
                    {
                        return;
                    }

                    NGUIEditorTools.BeginContents();

                    GUILayout.Space(3f);
                    NGUIEditorTools.DrawAdvancedSpriteField(mAtlas, sprite.name, SelectSprite, true);
                    GUILayout.Space(6f);

                    GUI.changed = false;

                    GUI.backgroundColor = greenColor;
                    NGUIEditorTools.IntVector sizeA = NGUIEditorTools.IntPair("Dimensions", "X", "Y", sprite.x, sprite.y);
                    NGUIEditorTools.IntVector sizeB = NGUIEditorTools.IntPair(null, "Width", "Height", sprite.width, sprite.height);

                    EditorGUILayout.Separator();
                    GUI.backgroundColor = blueColor;
                    NGUIEditorTools.IntVector borderA = NGUIEditorTools.IntPair("Border", "Left", "Right", sprite.borderLeft, sprite.borderRight);
                    NGUIEditorTools.IntVector borderB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.borderBottom, sprite.borderTop);

                    EditorGUILayout.Separator();
                    GUI.backgroundColor = Color.white;
                    NGUIEditorTools.IntVector padA = NGUIEditorTools.IntPair("Padding", "Left", "Right", sprite.paddingLeft, sprite.paddingRight);
                    NGUIEditorTools.IntVector padB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.paddingBottom, sprite.paddingTop);

                    if (GUI.changed)
                    {
                        NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas as Object);

                        sprite.x      = sizeA.x;
                        sprite.y      = sizeA.y;
                        sprite.width  = sizeB.x;
                        sprite.height = sizeB.y;

                        sprite.paddingLeft   = padA.x;
                        sprite.paddingRight  = padA.y;
                        sprite.paddingBottom = padB.x;
                        sprite.paddingTop    = padB.y;

                        sprite.borderLeft   = borderA.x;
                        sprite.borderRight  = borderA.y;
                        sprite.borderBottom = borderB.x;
                        sprite.borderTop    = borderB.y;

                        MarkSpriteAsDirty();
                        NGUITools.SetDirty(mAtlas as Object);
                    }

                    GUILayout.Space(3f);

                    GUILayout.BeginHorizontal();

                    if (GUILayout.Button("Duplicate"))
                    {
                        var se = UIAtlasMaker.DuplicateSprite(mAtlas, sprite.name);
                        if (se != null)
                        {
                            NGUISettings.selectedSprite = se.name;
                        }
                    }

                    if (GUILayout.Button("Save As..."))
                    {
                        var path = EditorUtility.SaveFilePanel("Save As",
                                                               NGUISettings.currentPath, sprite.name + ".png", "png");

                        if (!string.IsNullOrEmpty(path))
                        {
                            NGUISettings.currentPath = System.IO.Path.GetDirectoryName(path);
                            var se = UIAtlasMaker.ExtractSprite(mAtlas, sprite.name);

                            if (se != null)
                            {
                                var bytes = se.tex.EncodeToPNG();
                                File.WriteAllBytes(path, bytes);
                                //AssetDatabase.ImportAsset(path);
                                if (se.temporaryTexture)
                                {
                                    DestroyImmediate(se.tex);
                                }
                            }
                        }
                    }
                    GUILayout.EndHorizontal();
                    NGUIEditorTools.EndContents();
                }

                if (NGUIEditorTools.DrawHeader("Modify"))
                {
                    NGUIEditorTools.BeginContents();

                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(20f);
                    EditorGUILayout.BeginVertical();

                    NGUISettings.backgroundColor = EditorGUILayout.ColorField("Background", NGUISettings.backgroundColor);

                    if (GUILayout.Button("Add a Shadow"))
                    {
                        AddShadow(sprite);
                    }
                    if (GUILayout.Button("Add a Soft Outline"))
                    {
                        AddOutline(sprite);
                    }

                    if (GUILayout.Button("Add a Transparent Border"))
                    {
                        AddTransparentBorder(sprite);
                    }
                    if (GUILayout.Button("Add a Clamped Border"))
                    {
                        AddClampedBorder(sprite);
                    }
                    if (GUILayout.Button("Add a Tiled Border"))
                    {
                        AddTiledBorder(sprite);
                    }
                    EditorGUI.BeginDisabledGroup(!sprite.hasBorder);
                    if (GUILayout.Button("Crop Border"))
                    {
                        CropBorder(sprite);
                    }
                    EditorGUI.EndDisabledGroup();

                    EditorGUILayout.EndVertical();
                    GUILayout.Space(20f);
                    EditorGUILayout.EndHorizontal();

                    NGUIEditorTools.EndContents();
                }

                if (NGUIEditorTools.previousSelection != null)
                {
                    GUILayout.Space(3f);
                    GUI.backgroundColor = Color.green;

                    if (GUILayout.Button("<< Return to " + NGUIEditorTools.previousSelection.name))
                    {
                        NGUIEditorTools.SelectPrevious();
                    }
                    GUI.backgroundColor = Color.white;
                }
            }
        }
    }
コード例 #22
0
ファイル: UIAtlasInspector.cs プロジェクト: coolape/mibao
    /// <summary>
    /// Draw the inspector widget.
    /// </summary>

    public override void OnInspectorGUI()
    {
        NGUIEditorTools.SetLabelWidth(80f);
        mAtlas = target as UIAtlas;

        UISpriteData sprite = (mAtlas != null) ? mAtlas.GetSprite(NGUISettings.selectedSprite) : null;

        GUILayout.Space(6f);

        if (mAtlas.replacement != null)
        {
            mType        = AtlasType.Reference;
            mReplacement = mAtlas.replacement;
        }

        GUILayout.BeginHorizontal();
        AtlasType after = (AtlasType)EditorGUILayout.EnumPopup("Atlas Type", mType);

        NGUIEditorTools.DrawPadding();
        GUILayout.EndHorizontal();

        if (mType != after)
        {
            if (after == AtlasType.Normal)
            {
                mType = AtlasType.Normal;
                OnSelectAtlas(null);
            }
            else
            {
                mType = AtlasType.Reference;
            }
        }

        if (mType == AtlasType.Reference)
        {
            ComponentSelector.Draw <UIAtlas>(mAtlas.replacement, OnSelectAtlas, true);

            GUILayout.Space(6f);
            EditorGUILayout.HelpBox("You can have one atlas simply point to " +
                                    "another one. This is useful if you want to be " +
                                    "able to quickly replace the contents of one " +
                                    "atlas with another one, for example for " +
                                    "swapping an SD atlas with an HD one, or " +
                                    "replacing an English atlas with a Chinese " +
                                    "one. All the sprites referencing this atlas " +
                                    "will update their references to the new one.", MessageType.Info);

            if (mReplacement != mAtlas && mAtlas.replacement != mReplacement)
            {
                NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
                mAtlas.replacement = mReplacement;
                NGUITools.SetDirty(mAtlas);
            }
            return;
        }

        //GUILayout.Space(6f);
        Material mat = EditorGUILayout.ObjectField("Material", mAtlas.spriteMaterial, typeof(Material), false) as Material;

        if (mAtlas.spriteMaterial != mat)
        {
            NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
            mAtlas.spriteMaterial = mat;

            // Ensure that this atlas has valid import settings
            if (mAtlas.texture != null)
            {
                NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
            }

            mAtlas.MarkAsChanged();
        }

        #region         //add by chenbin
        if (mAtlas.isBorrowSpriteMode)
        {
            GUI.color = Color.green;
        }
        else
        {
            GUI.color = Color.white;
        }
        GUILayout.Label("\n===	=========================================");
        if (GUILayout.Button("说明"))
        {
            isShowBorrowModeDesc = !isShowBorrowModeDesc;
        }
        if (isShowBorrowModeDesc)
        {
            GUILayout.Label("勾选isBorrowSpriteMode时,表明该atlas是空atlas,\n" +
                            "当有sprit对象来borrow时,atlas会根据名字从\n" +
                            "设置的路径中去取得图片资源。\n" +
                            //"其中资源必须在Resources/下,\n" +
                            "另外atlas必须要引用一个material,\n" +
                            "就算引用的是个空material也行。\n");
        }

        if (mAtlas != null && runTimes == 0)
        {
            runTimes++;
            isBorrowMode = mAtlas.isBorrowSpriteMode;
            //			isUserUnity3DType = mAtlas.useUnity3DType;
        }
        mAtlas.isBorrowSpriteMode = EditorGUILayout.Toggle("isBorrowSpriteMode", mAtlas.isBorrowSpriteMode);
        if (isBorrowMode != mAtlas.isBorrowSpriteMode)
        {
            isBorrowMode = mAtlas.isBorrowSpriteMode;
            UnityEditor.EditorUtility.SetDirty(mAtlas.gameObject);
        }
        //		if (mAtlas.isBorrowSpriteMode) {
        //			mAtlas.useUnity3DType = EditorGUILayout.Toggle ("useUnity3DType", mAtlas.useUnity3DType);
        //			if (isUserUnity3DType != mAtlas.useUnity3DType) {
        //				isUserUnity3DType = mAtlas.useUnity3DType;
        //				UnityEditor.EditorUtility.SetDirty (NGUISettings.atlas.gameObject);
        //			}
        //		}
        GUILayout.Label("============================================\n");
        GUI.color = Color.white;
        if (GUILayout.Button("Clean items if no png"))
        {
            if (EditorUtility.DisplayDialog("Alert", "Really ?", "Do it now!", "NO"))
            {
                UISpriteData        item = null;
                List <UISpriteData> list = new List <UISpriteData> ();
                for (int i = 0; i < mAtlas.spriteList.Count; i++)
                {
                    item = mAtlas.spriteList [i];
                    string path = Application.dataPath + "/" + item.path;
                    path = path.Replace("/upgradeRes/", "/upgradeRes4Dev/");
                    path = path.Replace("/upgradeRes4Publish/", "/upgradeRes4Dev/");
                    if (!File.Exists(path))
                    {
                        Debug.Log(path);
                        list.Add(item);
                    }
                }
                deleteSprites(list);
            }
        }
        #endregion                                    //end ======add by chenbin

        if (mat != null || mAtlas.isBorrowSpriteMode) // modify by chenbin
        {
            TextAsset ta = EditorGUILayout.ObjectField("TP Import", null, typeof(TextAsset), false) as TextAsset;

            if (ta != null)
            {
                // Ensure that this atlas has valid import settings
                if (mAtlas.texture != null)
                {
                    NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
                }

                NGUIEditorTools.RegisterUndo("Import Sprites", mAtlas);
                NGUIJson.LoadSpriteData(mAtlas, ta);
                if (sprite != null)
                {
                    sprite = mAtlas.GetSprite(sprite.name);
                }
                mAtlas.MarkAsChanged();
            }

            float pixelSize = EditorGUILayout.FloatField("Pixel Size", mAtlas.pixelSize, GUILayout.Width(120f));

            if (pixelSize != mAtlas.pixelSize)
            {
                NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
                mAtlas.pixelSize = pixelSize;
            }
        }

        if (mAtlas.spriteMaterial != null || mAtlas.isBorrowSpriteMode)                 //modify by chenbin
        {
            Color blueColor  = new Color(0f, 0.7f, 1f, 1f);
            Color greenColor = new Color(0.4f, 1f, 0f, 1f);

            if (sprite == null && mAtlas.spriteList.Count > 0)
            {
                string spriteName = NGUISettings.selectedSprite;
                if (!string.IsNullOrEmpty(spriteName))
                {
                    sprite = mAtlas.GetSprite(spriteName);
                }
//				if (sprite == null) sprite = mAtlas.spriteList[0];  // delete by chenbin
                #region add by chenbin
                if (sprite == null)
                {
                    if (mAtlas.isBorrowSpriteMode)
                    {
                        sprite     = mAtlas.spriteList [0];
                        spriteName = sprite.name;
                        sprite     = mAtlas.borrowSpriteByname(spriteName, null);
                    }
                    else
                    {
                        sprite = mAtlas.spriteList [0];
                    }
                }
                #endregion
            }

            if (sprite != null)
            {
                if (sprite == null)
                {
                    return;
                }

//				Texture2D tex = mAtlas.spriteMaterial.mainTexture as Texture2D;	//delete by chenbin
                #region add by chenbin
                Texture2D tex = null;
                if (mAtlas != null)
                {
                    if (mAtlas.isBorrowSpriteMode)
                    {
                        if (sprite != null && sprite.material != null)
                        {
                            tex = sprite.material.mainTexture as Texture2D;
                        }
                    }
                    else
                    {
                        tex = mAtlas.spriteMaterial.mainTexture as Texture2D;
                    }
                }
                #endregion


//				if (tex != null)		//modify by chenbin
                if (tex != null || (mAtlas != null && mAtlas.isBorrowSpriteMode && sprite != null))                  //modify by chenbin
                {
                    if (!NGUIEditorTools.DrawHeader("Sprite Details"))
                    {
                        return;
                    }

                    NGUIEditorTools.BeginContents();

                    GUILayout.Space(3f);
                    NGUIEditorTools.DrawAdvancedSpriteField(mAtlas, sprite.name, SelectSprite, true);
                    GUILayout.Space(6f);

                    GUI.changed = false;

                    GUI.backgroundColor = greenColor;
                    NGUIEditorTools.IntVector sizeA = NGUIEditorTools.IntPair("Dimensions", "X", "Y", sprite.x, sprite.y);
                    NGUIEditorTools.IntVector sizeB = NGUIEditorTools.IntPair(null, "Width", "Height", sprite.width, sprite.height);

                    EditorGUILayout.Separator();
                    GUI.backgroundColor = blueColor;
                    NGUIEditorTools.IntVector borderA = NGUIEditorTools.IntPair("Border", "Left", "Right", sprite.borderLeft, sprite.borderRight);
                    NGUIEditorTools.IntVector borderB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.borderBottom, sprite.borderTop);

                    EditorGUILayout.Separator();
                    GUI.backgroundColor = Color.white;
                    NGUIEditorTools.IntVector padA = NGUIEditorTools.IntPair("Padding", "Left", "Right", sprite.paddingLeft, sprite.paddingRight);
                    NGUIEditorTools.IntVector padB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.paddingBottom, sprite.paddingTop);

                    if (GUI.changed)
                    {
                        NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);

                        sprite.x      = sizeA.x;
                        sprite.y      = sizeA.y;
                        sprite.width  = sizeB.x;
                        sprite.height = sizeB.y;

                        sprite.paddingLeft   = padA.x;
                        sprite.paddingRight  = padA.y;
                        sprite.paddingBottom = padB.x;
                        sprite.paddingTop    = padB.y;

                        sprite.borderLeft   = borderA.x;
                        sprite.borderRight  = borderA.y;
                        sprite.borderBottom = borderB.x;
                        sprite.borderTop    = borderB.y;

                        MarkSpriteAsDirty();
                    }

                    GUILayout.Space(3f);

                    GUILayout.BeginHorizontal();

                    if (GUILayout.Button("Duplicate"))
                    {
                        string newName = UIAtlasMaker.DuplicateSprite(mAtlas, sprite.name);                         // modify by chenbin
                        if (newName != null)
                        {
                            NGUISettings.selectedSprite = newName;                                              // modify by chenbin
                        }
                    }

                    if (GUILayout.Button("Save As..."))
                    {
#if UNITY_3_5
                        string path = EditorUtility.SaveFilePanel("Save As",
                                                                  NGUISettings.currentPath, sprite.name + ".png", "png");
#else
                        string path = EditorUtility.SaveFilePanelInProject("Save As",
                                                                           sprite.name + ".png", "png",
                                                                           "Extract sprite into which file?", NGUISettings.currentPath);
#endif

                        if (!string.IsNullOrEmpty(path))
                        {
                            NGUISettings.currentPath = System.IO.Path.GetDirectoryName(path);
                            UIAtlasMaker.SpriteEntry se = UIAtlasMaker.ExtractSprite(mAtlas, sprite.name);

                            if (se != null)
                            {
                                byte[] bytes = se.tex.EncodeToPNG();
                                File.WriteAllBytes(path, bytes);
                                AssetDatabase.ImportAsset(path);
                                if (se.temporaryTexture)
                                {
                                    DestroyImmediate(se.tex);
                                }
                            }
                        }
                    }
                    GUILayout.EndHorizontal();
                    NGUIEditorTools.EndContents();
                }

                if (NGUIEditorTools.DrawHeader("Modify"))
                {
                    NGUIEditorTools.BeginContents();

                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(20f);
                    EditorGUILayout.BeginVertical();

                    NGUISettings.backgroundColor = EditorGUILayout.ColorField("Background", NGUISettings.backgroundColor);

                    if (GUILayout.Button("Add a Shadow"))
                    {
                        AddShadow(sprite);
                    }
                    if (GUILayout.Button("Add a Soft Outline"))
                    {
                        AddOutline(sprite);
                    }

                    if (GUILayout.Button("Add a Transparent Border"))
                    {
                        AddTransparentBorder(sprite);
                    }
                    if (GUILayout.Button("Add a Clamped Border"))
                    {
                        AddClampedBorder(sprite);
                    }
                    if (GUILayout.Button("Add a Tiled Border"))
                    {
                        AddTiledBorder(sprite);
                    }
                    EditorGUI.BeginDisabledGroup(!sprite.hasBorder);
                    if (GUILayout.Button("Crop Border"))
                    {
                        CropBorder(sprite);
                    }
                    EditorGUI.EndDisabledGroup();

                    EditorGUILayout.EndVertical();
                    GUILayout.Space(20f);
                    EditorGUILayout.EndHorizontal();

                    NGUIEditorTools.EndContents();
                }

                if (NGUIEditorTools.previousSelection != null)
                {
                    GUILayout.Space(3f);
                    GUI.backgroundColor = Color.green;

                    if (GUILayout.Button("<< Return to " + NGUIEditorTools.previousSelection.name))
                    {
                        NGUIEditorTools.SelectPrevious();
                    }
                    GUI.backgroundColor = Color.white;
                }
            }
        }
    }
コード例 #23
0
    protected override bool ShouldDrawProperties()
    {
        if (target == null)
        {
            return(false);
        }

        if (Application.isPlaying == false && NGUIEditorTools.DrawHeader("Tex to Spr"))
        {
            NGUIEditorTools.BeginContents();
            GUILayout.BeginHorizontal();

            if (NGUIEditorTools.DrawPrefixButton("Atlas"))
            {
                ComponentSelector.Show <UIAtlas>(OnSelectAtlas);
            }

            UIAtlas curAtlas = NGUISettings.atlas;

            if (curAtlas != null)
            {
                GUILayout.Label(curAtlas.name, "HelpBox", GUILayout.Height(18f));
            }
            else
            {
                GUILayout.Label("No Atlas", "HelpBox", GUILayout.Height(18f));
            }

            GUILayout.FlexibleSpace();

            if (GUILayout.Button("ToS", GUILayout.Width(40f)))
            {
                if (curAtlas == null)
                {
                    CreateOwnAtlas();

                    curAtlas = NGUISettings.atlas;
                }

                List <UIAtlasMaker.SpriteEntry> entries = UIAtlasMaker.CreateSprites(new List <Texture>()
                {
                    mTex.mainTexture
                });
                UIAtlasMaker.ExtractSprites(curAtlas, entries);
                UIAtlasMaker.UpdateAtlas(curAtlas, entries);

                UISprite sprite = mTex.gameObject.AddComponent <UISprite>();
                sprite.atlas      = curAtlas;
                sprite.spriteName = mTex.mainTexture.name;

                sprite.type = mTex.type;

                UISpriteData data = sprite.GetAtlasSprite();
                data.SetBorder((int)mTex.border.w, (int)mTex.border.y, (int)mTex.border.x, (int)mTex.border.z);

                sprite.depth  = mTex.depth;
                sprite.width  = mTex.width;
                sprite.height = mTex.height;

                UITexture.DestroyImmediate(mTex);

                EditorGUIUtility.ExitGUI();

                return(false);
            }

            GUILayout.EndHorizontal();
            NGUIEditorTools.EndContents();
        }

        SerializedProperty sp = NGUIEditorTools.DrawProperty("Texture", serializedObject, "mTexture");

        NGUIEditorTools.DrawProperty("Material", serializedObject, "mMat");

        if (sp != null)
        {
            NGUISettings.texture = sp.objectReferenceValue as Texture;
        }

        if (mTex != null && (mTex.material == null || serializedObject.isEditingMultipleObjects))
        {
            NGUIEditorTools.DrawProperty("Shader", serializedObject, "mShader");
        }

        EditorGUI.BeginDisabledGroup(mTex == null || mTex.mainTexture == null || serializedObject.isEditingMultipleObjects);

        NGUIEditorTools.DrawRectProperty("UV Rect", serializedObject, "mRect");

        sp = serializedObject.FindProperty("mFixedAspect");
        bool before = sp.boolValue;

        NGUIEditorTools.DrawProperty("Fixed Aspect", sp);
        if (sp.boolValue != before)
        {
            (target as UIWidget).drawRegion = new Vector4(0f, 0f, 1f, 1f);
        }

        if (sp.boolValue)
        {
            EditorGUILayout.HelpBox("Note that Fixed Aspect mode is not compatible with Draw Region modifications done by sliders and progress bars.", MessageType.Info);
        }

        EditorGUI.EndDisabledGroup();

        return(true);
    }
コード例 #24
0
    /// <summary>
    /// Add a border around the sprite that copies the pixels from the opposite side, making it possible for the sprite to tile without seams.
    /// </summary>

    void AddTiledBorder(UISpriteData sprite)
    {
        var sprites = new List <UIAtlasMaker.SpriteEntry>();

        UIAtlasMaker.ExtractSprites(mAtlas, sprites);
        UIAtlasMaker.SpriteEntry se = null;

        for (int i = 0; i < sprites.Count; ++i)
        {
            if (sprites[i].name == sprite.name)
            {
                se = sprites[i];
                break;
            }
        }

        if (se != null)
        {
            int w1 = se.tex.width - se.borderLeft - se.borderRight;
            int h1 = se.tex.height - se.borderBottom - se.borderTop;

            int w2 = se.tex.width + 2;
            int h2 = se.tex.height + 2;

            var c1 = se.tex.GetPixels32();
            var c2 = new Color32[w2 * h2];

            for (int y2 = 0; y2 < h2; ++y2)
            {
                int y1 = se.borderBottom + NGUIMath.RepeatIndex(y2 - se.borderBottom - 1, h1);

                for (int x2 = 0; x2 < w2; ++x2)
                {
                    int x1 = se.borderLeft + NGUIMath.RepeatIndex(x2 - se.borderLeft - 1, w1);
                    c2[x2 + y2 * w2] = c1[x1 + y1 * se.tex.width];
                }
            }

            if (se.temporaryTexture)
            {
                DestroyImmediate(se.tex);
            }

            ++se.borderLeft;
            ++se.borderRight;
            ++se.borderTop;
            ++se.borderBottom;

            se.tex      = new Texture2D(w2, h2);
            se.tex.name = sprite.name;
            se.tex.SetPixels32(c2);
            se.tex.Apply();
            se.temporaryTexture = true;

            var before = NGUISettings.atlasTrimming;
            NGUISettings.atlasTrimming = false;
            UIAtlasMaker.UpdateAtlas(mAtlas, sprites);
            NGUISettings.atlasTrimming = before;

            DestroyImmediate(se.tex);
            se.tex = null;
        }
    }
コード例 #25
0
    /// <summary>
    /// Apply an effect to the font.
    /// </summary>

    void ApplyEffect(Effect effect, Color foreground, Color background)
    {
        BMFont bf      = mFont.bmFont;
        int    offsetX = 0;
        int    offsetY = 0;

        if (mFont.atlas != null)
        {
            UISpriteData sd = mFont.atlas.GetSprite(bf.spriteName);
            if (sd == null)
            {
                return;
            }
            offsetX = sd.x;
            offsetY = sd.y + mFont.texHeight - sd.paddingTop;
        }

        string    path  = AssetDatabase.GetAssetPath(mFont.texture);
        Texture2D bfTex = NGUIEditorTools.ImportTexture(path, true, true, false);

        Color32[] atlas = bfTex.GetPixels32();

        // First we need to extract textures for all the glyphs, making them bigger in the process
        List <BMGlyph>   glyphs        = bf.glyphs;
        List <Texture2D> glyphTextures = new List <Texture2D>(glyphs.Count);

        for (int i = 0, imax = glyphs.Count; i < imax; ++i)
        {
            BMGlyph glyph = glyphs[i];
            if (glyph.width < 1 || glyph.height < 1)
            {
                continue;
            }

            int width  = glyph.width;
            int height = glyph.height;

            if (effect == Effect.Outline || effect == Effect.Shadow || effect == Effect.Border)
            {
                width  += 2;
                height += 2;
                --glyph.offsetX;
                --glyph.offsetY;
            }
            else if (effect == Effect.Crop && width > 2 && height > 2)
            {
                width  -= 2;
                height -= 2;
                ++glyph.offsetX;
                ++glyph.offsetY;
            }

            int       size   = width * height;
            Color32[] colors = new Color32[size];
            Color32   clear  = background;
            clear.a = 0;
            for (int b = 0; b < size; ++b)
            {
                colors[b] = clear;
            }

            if (effect == Effect.Crop)
            {
                for (int y = 0; y < height; ++y)
                {
                    for (int x = 0; x < width; ++x)
                    {
                        int fx = x + glyph.x + offsetX + 1;
                        int fy = y + (mFont.texHeight - glyph.y - glyph.height) + 1;
                        if (mFont.atlas != null)
                        {
                            fy += bfTex.height - offsetY;
                        }
                        colors[x + y * width] = atlas[fx + fy * bfTex.width];
                    }
                }
            }
            else
            {
                for (int y = 0; y < glyph.height; ++y)
                {
                    for (int x = 0; x < glyph.width; ++x)
                    {
                        int fx = x + glyph.x + offsetX;
                        int fy = y + (mFont.texHeight - glyph.y - glyph.height);
                        if (mFont.atlas != null)
                        {
                            fy += bfTex.height - offsetY;
                        }

                        Color c = atlas[fx + fy * bfTex.width];

                        if (effect == Effect.Border)
                        {
                            colors[x + 1 + (y + 1) * width] = c;
                        }
                        else
                        {
                            if (effect == Effect.AlphaCurve)
                            {
                                c.a = Mathf.Clamp01(mCurve.Evaluate(c.a));
                            }

                            Color bg = background;
                            bg.a = (effect == Effect.BackgroundCurve) ? Mathf.Clamp01(mCurve.Evaluate(c.a)) : c.a;

                            Color fg = foreground;
                            fg.a = (effect == Effect.ForegroundCurve) ? Mathf.Clamp01(mCurve.Evaluate(c.a)) : c.a;

                            if (effect == Effect.Outline || effect == Effect.Shadow)
                            {
                                colors[x + 1 + (y + 1) * width] = Color.Lerp(bg, c, c.a);
                            }
                            else
                            {
                                colors[x + y * width] = Color.Lerp(bg, fg, c.a);
                            }
                        }
                    }
                }

                // Apply the appropriate affect
                if (effect == Effect.Shadow)
                {
                    NGUIEditorTools.AddShadow(colors, width, height, NGUISettings.backgroundColor);
                }
                else if (effect == Effect.Outline)
                {
                    NGUIEditorTools.AddDepth(colors, width, height, NGUISettings.backgroundColor);
                }
            }

            Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false);
            tex.SetPixels32(colors);
            tex.Apply();
            glyphTextures.Add(tex);
        }

        // Pack all glyphs into a new texture
        Texture2D final = new Texture2D(bfTex.width, bfTex.height, TextureFormat.ARGB32, false);

        Rect[] rects = final.PackTextures(glyphTextures.ToArray(), 1);
        final.Apply();

        // Make RGB channel use the background color (Unity makes it black by default)
        Color32[] fcs = final.GetPixels32();
        Color32   bc  = background;

        for (int i = 0, imax = fcs.Length; i < imax; ++i)
        {
            if (fcs[i].a == 0)
            {
                fcs[i].r = bc.r;
                fcs[i].g = bc.g;
                fcs[i].b = bc.b;
            }
        }

        final.SetPixels32(fcs);
        final.Apply();

        // Update the glyph rectangles
        int index = 0;
        int tw    = final.width;
        int th    = final.height;

        for (int i = 0, imax = glyphs.Count; i < imax; ++i)
        {
            BMGlyph glyph = glyphs[i];
            if (glyph.width < 1 || glyph.height < 1)
            {
                continue;
            }

            Rect rect = rects[index++];
            glyph.x      = Mathf.RoundToInt(rect.x * tw);
            glyph.y      = Mathf.RoundToInt(rect.y * th);
            glyph.width  = Mathf.RoundToInt(rect.width * tw);
            glyph.height = Mathf.RoundToInt(rect.height * th);
            glyph.y      = th - glyph.y - glyph.height;
        }

        // Update the font's texture dimensions
        mFont.texWidth  = final.width;
        mFont.texHeight = final.height;

        if (mFont.atlas == null)
        {
            // Save the final texture
            byte[] bytes = final.EncodeToPNG();
            NGUITools.DestroyImmediate(final);
            System.IO.File.WriteAllBytes(path, bytes);
            AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
        }
        else
        {
            // Update the atlas
            final.name = mFont.spriteName;
            bool val = NGUISettings.atlasTrimming;
            NGUISettings.atlasTrimming = false;
            UIAtlasMaker.AddOrUpdate(mFont.atlas, final);
            NGUISettings.atlasTrimming = val;
            NGUITools.DestroyImmediate(final);
        }

        // Cleanup
        for (int i = 0; i < glyphTextures.Count; ++i)
        {
            NGUITools.DestroyImmediate(glyphTextures[i]);
        }

        // Refresh all labels
        mFont.MarkAsChanged();
    }
コード例 #26
0
    /// <summary>
    /// Draw the custom wizard.
    /// </summary>

    void OnGUI()
    {
        NGUIEditorTools.SetLabelWidth(80f);

        if (NGUISettings.atlas == null)
        {
            mMainTexCache = null;
            GUILayout.Label("No Atlas selected.", "LODLevelNotifyText");
        }
        else
        {
            UIAtlas atlas = NGUISettings.atlas;
            bool    close = false;
            GUILayout.Label(atlas.name + " Sprites", "LODLevelNotifyText");
            NGUIEditorTools.DrawSeparator();

            GUILayout.BeginHorizontal();
            if (GUILayout.Button((mShowAlpha ? "Hide" : "Show") + " Alpha", GUILayout.Width(80)))
            {
                mShowAlpha = !mShowAlpha;
            }
            GUILayout.Space(4f);

            string before = NGUISettings.partialSprite;
            string after  = EditorGUILayout.TextField("", before, "SearchTextField");
            if (before != after)
            {
                NGUISettings.partialSprite = after;
            }

            if (GUILayout.Button("", "SearchCancelButton", GUILayout.Width(18f)))
            {
                NGUISettings.partialSprite = "";
                GUIUtility.keyboardControl = 0;
            }
            GUILayout.Space(84f);
            GUILayout.EndHorizontal();

            Texture2D tex = atlas.texture as Texture2D;
            if (mShowAlpha)
            {
                if (tex != mMainTexCache)
                {
                    mMainTexCache = tex;
                    if (atlas.alphaTexture != null)
                    {
                        Texture2D agbTex   = NGUIEditorTools.ImportTexture(mMainTexCache, true, false, false);
                        Texture2D alphaTex = NGUIEditorTools.ImportTexture(atlas.alphaTexture, true, false, false);
                        mTex = UIAtlasMaker.AlphaMerge(agbTex, alphaTex);
                        NGUIEditorTools.ImportTexture(agbTex, false, false, true);
                        NGUIEditorTools.ImportTexture(alphaTex, false, false, false);
                    }
                    else
                    {
                        mTex = mMainTexCache;
                    }
                }
                tex = mTex;
            }

            if (tex == null)
            {
                GUILayout.Label("The atlas doesn't have a texture to work with");
                return;
            }

            BetterList <string> sprites = atlas.GetListOfSprites(NGUISettings.partialSprite);

            float size   = 80f;
            float padded = size + 10f;
#if UNITY_4_7
            int screenWidth = Screen.width;
#else
            int screenWidth = (int)EditorGUIUtility.currentViewWidth;
#endif
            int columns = Mathf.FloorToInt(screenWidth / padded);
            if (columns < 1)
            {
                columns = 1;
            }

            int  offset = 0;
            Rect rect   = new Rect(10f, 0, size, size);

            GUILayout.Space(10f);
            mPos = GUILayout.BeginScrollView(mPos);
            int rows = 1;

            while (offset < sprites.size)
            {
                GUILayout.BeginHorizontal();
                {
                    int col = 0;
                    rect.x = 10f;

                    for (; offset < sprites.size; ++offset)
                    {
                        UISpriteData sprite = atlas.GetSprite(sprites[offset]);
                        if (sprite == null)
                        {
                            continue;
                        }

                        // Button comes first
                        if (GUI.Button(rect, ""))
                        {
                            if (Event.current.button == 0)
                            {
                                float delta = Time.realtimeSinceStartup - mClickTime;
                                mClickTime = Time.realtimeSinceStartup;

                                if (NGUISettings.selectedSprite != sprite.name)
                                {
                                    if (mSprite != null)
                                    {
                                        NGUIEditorTools.RegisterUndo("Atlas Selection", mSprite);
                                        mSprite.MakePixelPerfect();
                                        EditorUtility.SetDirty(mSprite.gameObject);
                                    }

                                    NGUISettings.selectedSprite = sprite.name;
                                    NGUIEditorTools.RepaintSprites();
                                    if (mCallback != null)
                                    {
                                        mCallback(sprite.name);
                                    }
                                }
                                else if (delta < 0.5f)
                                {
                                    close = true;
                                }
                            }
                            else
                            {
                                NGUIContextMenu.AddItem("Edit", false, EditSprite, sprite);
                                NGUIContextMenu.AddItem("Delete", false, DeleteSprite, sprite);
                                NGUIContextMenu.Show();
                            }
                        }

                        if (Event.current.type == EventType.Repaint)
                        {
                            // On top of the button we have a checkboard grid
                            NGUIEditorTools.DrawTiledTexture(rect, NGUIEditorTools.backdropTexture);
                            Rect uv = new Rect(sprite.x, sprite.y, sprite.width, sprite.height);
                            uv = NGUIMath.ConvertToTexCoords(uv, atlas.width, atlas.height);

                            // Calculate the texture's scale that's needed to display the sprite in the clipped area
                            float scaleX = rect.width / uv.width;
                            float scaleY = rect.height / uv.height;

                            // Stretch the sprite so that it will appear proper
                            float aspect   = (scaleY / scaleX) / ((float)atlas.height / atlas.width);
                            Rect  clipRect = rect;

                            if (aspect != 1f)
                            {
                                if (aspect < 1f)
                                {
                                    // The sprite is taller than it is wider
                                    float padding = size * (1f - aspect) * 0.5f;
                                    clipRect.xMin += padding;
                                    clipRect.xMax -= padding;
                                }
                                else
                                {
                                    // The sprite is wider than it is taller
                                    float padding = size * (1f - 1f / aspect) * 0.5f;
                                    clipRect.yMin += padding;
                                    clipRect.yMax -= padding;
                                }
                            }

                            GUI.DrawTextureWithTexCoords(clipRect, tex, uv);

                            // Draw the selection
                            if (NGUISettings.selectedSprite == sprite.name)
                            {
                                NGUIEditorTools.DrawOutline(rect, new Color(0.4f, 1f, 0f, 1f));
                            }
                        }

                        GUI.backgroundColor = new Color(1f, 1f, 1f, 0.5f);
                        GUI.contentColor    = new Color(1f, 1f, 1f, 0.7f);
                        GUI.Label(new Rect(rect.x, rect.y + rect.height, rect.width, 32f), sprite.name, "ProgressBarBack");
                        GUI.contentColor    = Color.white;
                        GUI.backgroundColor = Color.white;

                        if (++col >= columns)
                        {
                            ++offset;
                            break;
                        }
                        rect.x += padded;
                    }
                }
                GUILayout.EndHorizontal();
                GUILayout.Space(padded);
                rect.y += padded + 26;
                ++rows;
            }
            GUILayout.Space(rows * 26);
            GUILayout.EndScrollView();

            if (close)
            {
                Close();
            }
        }
    }
コード例 #27
0
    /// <summary>
    /// Draw the UI for this tool.
    /// </summary>

    void OnGUI()
    {
        string prefabPath = "";
        string matPath    = "";

        if (NGUISettings.font != null && NGUISettings.font.name == NGUISettings.fontName)
        {
            prefabPath = AssetDatabase.GetAssetPath(NGUISettings.font.gameObject.GetInstanceID());
            if (NGUISettings.font.material != null)
            {
                matPath = AssetDatabase.GetAssetPath(NGUISettings.font.material.GetInstanceID());
            }
        }

        // Assume default values if needed
        if (string.IsNullOrEmpty(NGUISettings.fontName))
        {
            NGUISettings.fontName = "New Font";
        }
        if (string.IsNullOrEmpty(prefabPath))
        {
            prefabPath = NGUIEditorTools.GetSelectionFolder() + NGUISettings.fontName + ".prefab";
        }
        if (string.IsNullOrEmpty(matPath))
        {
            matPath = NGUIEditorTools.GetSelectionFolder() + NGUISettings.fontName + ".mat";
        }

        NGUIEditorTools.SetLabelWidth(80f);
        NGUIEditorTools.DrawHeader("Input", true);
        NGUIEditorTools.BeginContents();

        GUILayout.BeginHorizontal();
        mType = (FontType)EditorGUILayout.EnumPopup("Type", mType);
        GUILayout.Space(18f);
        GUILayout.EndHorizontal();
        int create = 0;

        if (mType == FontType.Dynamic)
        {
            NGUISettings.dynamicFont = EditorGUILayout.ObjectField("Font TTF", NGUISettings.dynamicFont, typeof(Font), false) as Font;

            GUILayout.BeginHorizontal();
            NGUISettings.dynamicFontSize  = EditorGUILayout.IntField("Font Size", NGUISettings.dynamicFontSize, GUILayout.Width(120f));
            NGUISettings.dynamicFontStyle = (FontStyle)EditorGUILayout.EnumPopup(NGUISettings.dynamicFontStyle);
            GUILayout.Space(18f);
            GUILayout.EndHorizontal();
            NGUIEditorTools.EndContents();

            if (NGUISettings.dynamicFont != null)
            {
                NGUIEditorTools.DrawHeader("Output", true);

                NGUIEditorTools.BeginContents();
                GUILayout.BeginHorizontal();
                GUILayout.Label("Font Name", GUILayout.Width(76f));
                GUI.backgroundColor   = Color.white;
                NGUISettings.fontName = GUILayout.TextField(NGUISettings.fontName);

#if !UNITY_3_5
                if (NGUISettings.dynamicFont != null)
                {
                    GameObject go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;

                    if (go != null)
                    {
                        if (go.GetComponent <UIFont>() != null)
                        {
                            GUI.backgroundColor = Color.red;
                            if (GUILayout.Button("Replace", GUILayout.Width(70f)))
                            {
                                create = 1;
                            }
                        }
                        else
                        {
                            GUI.backgroundColor = Color.grey;
                            GUILayout.Button("Rename", GUILayout.Width(70f));
                        }
                    }
                    else
                    {
                        GUI.backgroundColor = Color.green;
                        if (GUILayout.Button("Create", GUILayout.Width(70f)))
                        {
                            create = 1;
                        }
                    }

                    GUI.backgroundColor = Color.white;
                }
#endif
                GUILayout.EndHorizontal();
                NGUIEditorTools.EndContents();
            }

#if UNITY_3_5
            EditorGUILayout.HelpBox("Dynamic fonts require Unity 4.0 or higher.", MessageType.Error);
#else
            // Helpful info
            if (NGUISettings.dynamicFont == null)
            {
                EditorGUILayout.HelpBox("Dynamic font creation happens right in Unity. Simply specify the TrueType font to be used as source.", MessageType.Info);
            }
            EditorGUILayout.HelpBox("Please note that dynamic fonts can't be made a part of an atlas, and using dynamic fonts will result in at least one extra draw call.", MessageType.Warning);
#endif
        }
        else
        {
            NGUISettings.fontData    = EditorGUILayout.ObjectField("Font Data", NGUISettings.fontData, typeof(TextAsset), false) as TextAsset;
            NGUISettings.fontTexture = EditorGUILayout.ObjectField("Texture", NGUISettings.fontTexture, typeof(Texture2D), false) as Texture2D;
            NGUIEditorTools.EndContents();

            // Draw the atlas selection only if we have the font data and texture specified, just to make it easier
            if (NGUISettings.fontData != null && NGUISettings.fontTexture != null)
            {
                NGUIEditorTools.DrawHeader("Output", true);
                NGUIEditorTools.BeginContents();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Font Name", GUILayout.Width(76f));
                GUI.backgroundColor   = Color.white;
                NGUISettings.fontName = GUILayout.TextField(NGUISettings.fontName);
                GUILayout.EndHorizontal();

                ComponentSelector.Draw <UIFont>("Select", NGUISettings.font, OnSelectFont);
                ComponentSelector.Draw <UIAtlas>(NGUISettings.atlas, OnSelectAtlas);
                NGUIEditorTools.EndContents();
            }

            // Helpful info
            if (NGUISettings.fontData == null)
            {
                EditorGUILayout.HelpBox("The bitmap font creation mostly takes place outside of Unity. You can use BMFont on " +
                                        "Windows or your choice of Glyph Designer or the less expensive bmGlyph on the Mac.\n\n" +
                                        "Either of these tools will create a FNT file for you that you will drag & drop into the field above.", MessageType.Info);
            }
            else if (NGUISettings.fontTexture == null)
            {
                EditorGUILayout.HelpBox("When exporting your font, you should get two files: the TXT, and the texture. Only one texture can be used per font.", MessageType.Info);
            }
            else if (NGUISettings.atlas == null)
            {
                EditorGUILayout.HelpBox("You can create a font that doesn't use a texture atlas. This will mean that the text " +
                                        "labels using this font will generate an extra draw call, and will need to be sorted by " +
                                        "adjusting the Z instead of the Depth.\n\nIf you do specify an atlas, the font's texture will be added to it automatically.", MessageType.Info);

                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                GUI.backgroundColor = Color.red;
                if (GUILayout.Button("Create a Font without an Atlas", GUILayout.Width(200f)))
                {
                    create = 2;
                }
                GUI.backgroundColor = Color.white;
                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();
            }
            else
            {
                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();

                GameObject go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;

                if (go != null)
                {
                    if (go.GetComponent <UIFont>() != null)
                    {
                        GUI.backgroundColor = Color.red;
                        if (GUILayout.Button("Replace the Font", GUILayout.Width(140f)))
                        {
                            create = 3;
                        }
                    }
                    else
                    {
                        GUI.backgroundColor = Color.grey;
                        GUILayout.Button("Rename Your Font", GUILayout.Width(140f));
                    }
                }
                else
                {
                    GUI.backgroundColor = Color.green;
                    if (GUILayout.Button("Create the Font", GUILayout.Width(140f)))
                    {
                        create = 3;
                    }
                }
                GUI.backgroundColor = Color.white;
                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();
            }
        }

        if (create != 0)
        {
            GameObject go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;

            if (go == null || EditorUtility.DisplayDialog("Are you sure?", "Are you sure you want to replace the contents of the " +
                                                          NGUISettings.fontName + " font with the currently selected values? This action can't be undone.", "Yes", "No"))
            {
                // Try to load the material
                Material mat = null;

                // Non-atlased font
                if (create == 2)
                {
                    mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;

                    // If the material doesn't exist, create it
                    if (mat == null)
                    {
                        Shader shader = Shader.Find("Unlit/Transparent Colored");
                        mat = new Material(shader);

                        // Save the material
                        AssetDatabase.CreateAsset(mat, matPath);
                        AssetDatabase.Refresh();

                        // Load the material so it's usable
                        mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
                    }
                    mat.mainTexture = NGUISettings.fontTexture;
                }
                else if (create != 1)
                {
                    UIAtlasMaker.AddOrUpdate(NGUISettings.atlas, NGUISettings.fontTexture);
                }

                // Font doesn't exist yet
                if (go == null || go.GetComponent <UIFont>() == null)
                {
                    // Create a new prefab for the atlas
                    Object prefab = PrefabUtility.CreateEmptyPrefab(prefabPath);

                    // Create a new game object for the font
                    go = new GameObject(NGUISettings.fontName);
                    NGUISettings.font = go.AddComponent <UIFont>();
                    CreateFont(NGUISettings.font, create, mat);

                    // Update the prefab
                    PrefabUtility.ReplacePrefab(go, prefab);
                    DestroyImmediate(go);
                    AssetDatabase.Refresh();

                    // Select the atlas
                    go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
                    NGUISettings.font = go.GetComponent <UIFont>();
                }
                else
                {
                    NGUISettings.font = go.GetComponent <UIFont>();
                    CreateFont(NGUISettings.font, create, mat);
                }
                MarkAsChanged();
            }
        }
    }
コード例 #28
0
    /// <summary>
    /// Draw the UI for this tool.
    /// </summary>

    void OnGUI()
    {
        Object fnt    = NGUISettings.ambigiousFont;
        UIFont uiFont = (fnt as UIFont);

        NGUIEditorTools.SetLabelWidth(80f);
        GUILayout.Space(3f);

        NGUIEditorTools.DrawHeader("Input", true);
        NGUIEditorTools.BeginContents(false);

        GUILayout.BeginHorizontal();
        mType = (FontType)EditorGUILayout.EnumPopup("Type", mType, GUILayout.MinWidth(200f));
        NGUIEditorTools.DrawPadding();
        GUILayout.EndHorizontal();
        Create create = Create.None;

        if (mType == FontType.ImportedBitmap)
        {
            NGUISettings.fontData    = EditorGUILayout.ObjectField("Font Data", NGUISettings.fontData, typeof(TextAsset), false) as TextAsset;
            NGUISettings.fontTexture = EditorGUILayout.ObjectField("Texture", NGUISettings.fontTexture, typeof(Texture2D), false, GUILayout.Width(140f)) as Texture2D;
            NGUIEditorTools.EndContents();

            // Draw the atlas selection only if we have the font data and texture specified, just to make it easier
            EditorGUI.BeginDisabledGroup(NGUISettings.fontData == null || NGUISettings.fontTexture == null);
            {
                NGUIEditorTools.DrawHeader("Output", true);
                NGUIEditorTools.BeginContents(false);
                ComponentSelector.Draw <UIAtlas>(NGUISettings.atlas, OnSelectAtlas, false);
                NGUIEditorTools.EndContents();
            }
            EditorGUI.EndDisabledGroup();

            if (NGUISettings.fontData == null)
            {
                EditorGUILayout.HelpBox("To create a font from a previously exported FNT file, you need to use BMFont on " +
                                        "Windows or your choice of Glyph Designer or the less expensive bmGlyph on the Mac.\n\n" +
                                        "Either of these tools will create a FNT file for you that you will drag & drop into the field above.", MessageType.Info);
            }
            else if (NGUISettings.fontTexture == null)
            {
                EditorGUILayout.HelpBox("When exporting your font, you should get two files: the FNT, and the texture. Only one texture can be used per font.", MessageType.Info);
            }
            else if (NGUISettings.atlas == null)
            {
                EditorGUILayout.HelpBox("You can create a font that doesn't use a texture atlas. This will mean that the text " +
                                        "labels using this font will generate an extra draw call.\n\nIf you do specify an atlas, the font's texture will be added to it automatically.", MessageType.Info);
            }

            EditorGUI.BeginDisabledGroup(NGUISettings.fontData == null || NGUISettings.fontTexture == null);
            {
                GUILayout.BeginHorizontal();
                GUILayout.Space(20f);
                if (GUILayout.Button("Create the Font"))
                {
                    create = Create.Import;
                }
                GUILayout.Space(20f);
                GUILayout.EndHorizontal();
            }
            EditorGUI.EndDisabledGroup();
        }
        else
        {
            GUILayout.BeginHorizontal();
            if (NGUIEditorTools.DrawPrefixButton("Source"))
            {
                ComponentSelector.Show <Font>(OnUnityFont, new string[] { ".ttf", ".otf" });
            }

            Font ttf = EditorGUILayout.ObjectField(NGUISettings.ambigiousFont as Font, typeof(Font), false) as Font;
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            {
                NGUISettings.fontSize = EditorGUILayout.IntField("Size", NGUISettings.fontSize, GUILayout.Width(120f));

                if (mType == FontType.Dynamic)
                {
                    NGUISettings.fontStyle = (FontStyle)EditorGUILayout.EnumPopup(NGUISettings.fontStyle);
                    NGUIEditorTools.DrawPadding();
                }
            }
            GUILayout.EndHorizontal();

            // Choose the font style if there are multiple faces present
            if (mType == FontType.GeneratedBitmap)
            {
                if (!FreeType.isPresent)
                {
                    string filename = (Application.platform == RuntimePlatform.WindowsEditor) ? "FreeType.dll" : "FreeType.dylib";

                    EditorGUILayout.HelpBox("Assets/NGUI/Editor/" + filename + " is missing", MessageType.Error);

                    GUILayout.BeginHorizontal();
                    GUILayout.Space(20f);

                    if (GUILayout.Button("Find " + filename))
                    {
                        string path = EditorUtility.OpenFilePanel("Find " + filename, NGUISettings.currentPath,
                                                                  (Application.platform == RuntimePlatform.WindowsEditor) ? "dll" : "dylib");

                        if (!string.IsNullOrEmpty(path))
                        {
                            if (System.IO.Path.GetFileName(path) == filename)
                            {
                                NGUISettings.currentPath    = System.IO.Path.GetDirectoryName(path);
                                NGUISettings.pathToFreeType = path;
                            }
                            else
                            {
                                Debug.LogError("The library must be named '" + filename + "'");
                            }
                        }
                    }
                    GUILayout.Space(20f);
                    GUILayout.EndHorizontal();
                }
                else if (ttf != null)
                {
                    string[] faces = FreeType.GetFaces(ttf);

                    if (faces != null)
                    {
                        if (mFaceIndex >= faces.Length)
                        {
                            mFaceIndex = 0;
                        }

                        if (faces.Length > 1)
                        {
                            GUILayout.Label("Style", EditorStyles.boldLabel);
                            for (int i = 0; i < faces.Length; ++i)
                            {
                                GUILayout.BeginHorizontal();
                                GUILayout.Space(10f);
                                if (DrawOption(i == mFaceIndex, " " + faces[i]))
                                {
                                    mFaceIndex = i;
                                }
                                GUILayout.EndHorizontal();
                            }
                        }
                    }

                    GUILayout.Label("Characters", EditorStyles.boldLabel);

                    CharacterMap cm = characterMap;

                    GUILayout.BeginHorizontal(GUILayout.Width(100f));
                    GUILayout.BeginVertical();
                    GUI.changed = false;
                    if (DrawOption(cm == CharacterMap.Numeric, " Numeric"))
                    {
                        cm = CharacterMap.Numeric;
                    }
                    if (DrawOption(cm == CharacterMap.Ascii, " ASCII"))
                    {
                        cm = CharacterMap.Ascii;
                    }
                    if (DrawOption(cm == CharacterMap.Latin, " Latin"))
                    {
                        cm = CharacterMap.Latin;
                    }
                    if (DrawOption(cm == CharacterMap.Custom, " Custom"))
                    {
                        cm = CharacterMap.Custom;
                    }
                    if (GUI.changed)
                    {
                        characterMap = cm;
                    }
                    GUILayout.EndVertical();

                    EditorGUI.BeginDisabledGroup(cm != CharacterMap.Custom);
                    {
                        if (cm != CharacterMap.Custom)
                        {
                            string chars = "";

                            if (cm == CharacterMap.Ascii)
                            {
                                for (int i = 33; i < 127; ++i)
                                {
                                    chars += System.Convert.ToChar(i);
                                }
                            }
                            else if (cm == CharacterMap.Numeric)
                            {
                                chars = "01234567890";
                            }
                            else if (cm == CharacterMap.Latin)
                            {
                                for (int i = 33; i < 127; ++i)
                                {
                                    chars += System.Convert.ToChar(i);
                                }

                                for (int i = 161; i < 256; ++i)
                                {
                                    chars += System.Convert.ToChar(i);
                                }
                            }

                            NGUISettings.charsToInclude = chars;
                        }

                        GUI.changed = false;

                        string text = NGUISettings.charsToInclude;

                        if (cm == CharacterMap.Custom)
                        {
                            text = EditorGUILayout.TextArea(text, GUI.skin.textArea,
                                                            GUILayout.Height(80f), GUILayout.Width(Screen.width - 100f));
                        }
                        else
                        {
                            GUILayout.Label(text, GUI.skin.textArea,
                                            GUILayout.Height(80f), GUILayout.Width(Screen.width - 100f));
                        }

                        if (GUI.changed)
                        {
                            string final = "";

                            for (int i = 0; i < text.Length; ++i)
                            {
                                char c = text[i];
                                if (c < 33)
                                {
                                    continue;
                                }
                                string s = c.ToString();
                                if (!final.Contains(s))
                                {
                                    final += s;
                                }
                            }

                            if (final.Length > 0)
                            {
                                char[] chars = final.ToCharArray();
                                System.Array.Sort(chars);
                                final = new string(chars);
                            }
                            else
                            {
                                final = "";
                            }

                            NGUISettings.charsToInclude = final;
                        }
                    }
                    EditorGUI.EndDisabledGroup();
                    GUILayout.EndHorizontal();
                }
            }
            NGUIEditorTools.EndContents();

            if (mType == FontType.Dynamic)
            {
                EditorGUI.BeginDisabledGroup(ttf == null);
                GUILayout.BeginHorizontal();
                GUILayout.Space(20f);
                if (GUILayout.Button("Create the Font"))
                {
                    create = Create.Dynamic;
                }
                GUILayout.Space(20f);
                GUILayout.EndHorizontal();
                EditorGUI.EndDisabledGroup();
#if UNITY_3_5
                EditorGUILayout.HelpBox("Dynamic fonts require Unity 4.0 or higher.", MessageType.Error);
#else
                // Helpful info
                if (ttf == null)
                {
                    EditorGUILayout.HelpBox("You don't have to create a UIFont to use dynamic fonts. You can just reference the Unity Font directly on the label.", MessageType.Info);
                }
                EditorGUILayout.HelpBox("Please note that dynamic fonts can't be made a part of an atlas, and using dynamic fonts will result in at least one extra draw call.", MessageType.Warning);
#endif
            }
            else
            {
                bool isBuiltIn = (ttf != null) && string.IsNullOrEmpty(UnityEditor.AssetDatabase.GetAssetPath(ttf));

                // Draw the atlas selection only if we have the font data and texture specified, just to make it easier
                EditorGUI.BeginDisabledGroup(ttf == null || isBuiltIn || !FreeType.isPresent);
                {
                    NGUIEditorTools.DrawHeader("Output", true);
                    NGUIEditorTools.BeginContents(false);
                    ComponentSelector.Draw <UIAtlas>(NGUISettings.atlas, OnSelectAtlas, false);
                    NGUIEditorTools.EndContents();

                    if (ttf == null)
                    {
                        EditorGUILayout.HelpBox("You can create a bitmap font by specifying a dynamic font to use as the source.", MessageType.Info);
                    }
                    else if (isBuiltIn)
                    {
                        EditorGUILayout.HelpBox("You chose an embedded font. You can't create a bitmap font from an embedded resource.", MessageType.Warning);
                    }
                    else if (NGUISettings.atlas == null)
                    {
                        EditorGUILayout.HelpBox("You can create a font that doesn't use a texture atlas. This will mean that the text " +
                                                "labels using this font will generate an extra draw call.\n\nIf you do specify an atlas, the font's texture will be added to it automatically.", MessageType.Info);
                    }

                    GUILayout.BeginHorizontal();
                    GUILayout.Space(20f);
                    if (GUILayout.Button("Create the Font"))
                    {
                        create = Create.Bitmap;
                    }
                    GUILayout.Space(20f);
                    GUILayout.EndHorizontal();
                }
                EditorGUI.EndDisabledGroup();
            }
        }

        if (create == Create.None)
        {
            return;
        }

        // Open the "Save As" file dialog
#if UNITY_3_5
        string prefabPath = EditorUtility.SaveFilePanel("Save As",
                                                        NGUISettings.currentPath, "New Font.prefab", "prefab");
#else
        string prefabPath = EditorUtility.SaveFilePanelInProject("Save As",
                                                                 "New Font.prefab", "prefab", "Save font as...", NGUISettings.currentPath);
#endif
        if (string.IsNullOrEmpty(prefabPath))
        {
            return;
        }
        NGUISettings.currentPath = System.IO.Path.GetDirectoryName(prefabPath);

        // Load the font's prefab
        GameObject go     = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
        Object     prefab = null;
        string     fontName;

        // Font doesn't exist yet
        if (go == null || go.GetComponent <UIFont>() == null)
        {
            // Create a new prefab for the atlas
            prefab = PrefabUtility.CreateEmptyPrefab(prefabPath);

            fontName = prefabPath.Replace(".prefab", "");
            fontName = fontName.Substring(prefabPath.LastIndexOfAny(new char[] { '/', '\\' }) + 1);

            // Create a new game object for the font
            go     = new GameObject(fontName);
            uiFont = go.AddComponent <UIFont>();
        }
        else
        {
            uiFont   = go.GetComponent <UIFont>();
            fontName = go.name;
        }

        if (create == Create.Dynamic)
        {
            uiFont.atlas            = null;
            uiFont.dynamicFont      = NGUISettings.dynamicFont;
            uiFont.dynamicFontStyle = NGUISettings.fontStyle;
            uiFont.defaultSize      = NGUISettings.fontSize;
        }
        else if (create == Create.Import)
        {
            Material mat = null;

            if (NGUISettings.atlas != null)
            {
                // Add the font's texture to the atlas
                UIAtlasMaker.AddOrUpdate(NGUISettings.atlas, NGUISettings.fontTexture);
            }
            else
            {
                // Create a material for the font
                string matPath = prefabPath.Replace(".prefab", ".mat");
                mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;

                // If the material doesn't exist, create it
                if (mat == null)
                {
                    Shader shader = Shader.Find("Unlit/Transparent Colored");
                    mat = new Material(shader);

                    // Save the material
                    AssetDatabase.CreateAsset(mat, matPath);
                    AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

                    // Load the material so it's usable
                    mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
                }

                mat.mainTexture = NGUISettings.fontTexture;
            }

            uiFont.dynamicFont = null;
            BMFontReader.Load(uiFont.bmFont, NGUITools.GetHierarchy(uiFont.gameObject), NGUISettings.fontData.bytes);

            if (NGUISettings.atlas == null)
            {
                uiFont.atlas    = null;
                uiFont.material = mat;
            }
            else
            {
                uiFont.spriteName = NGUISettings.fontTexture.name;
                uiFont.atlas      = NGUISettings.atlas;
            }
            NGUISettings.fontSize = uiFont.defaultSize;
        }
        else if (create == Create.Bitmap)
        {
            // Create the bitmap font
            BMFont    bmFont;
            Texture2D tex;

            if (FreeType.CreateFont(
                    NGUISettings.dynamicFont,
                    NGUISettings.fontSize, mFaceIndex,
                    NGUISettings.charsToInclude, out bmFont, out tex))
            {
                uiFont.bmFont = bmFont;
                tex.name      = fontName;

                if (NGUISettings.atlas != null)
                {
                    // Add this texture to the atlas and destroy it
                    UIAtlasMaker.AddOrUpdate(NGUISettings.atlas, tex);
                    NGUITools.DestroyImmediate(tex);
                    NGUISettings.fontTexture = null;
                    tex = null;

                    uiFont.atlas      = NGUISettings.atlas;
                    uiFont.spriteName = fontName;
                }
                else
                {
                    string texPath = prefabPath.Replace(".prefab", ".png");
                    string matPath = prefabPath.Replace(".prefab", ".mat");

                    byte[]     png = tex.EncodeToPNG();
                    FileStream fs  = File.OpenWrite(texPath);
                    fs.Write(png, 0, png.Length);
                    fs.Close();

                    // See if the material already exists
                    Material mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;

                    // If the material doesn't exist, create it
                    if (mat == null)
                    {
                        Shader shader = Shader.Find("Unlit/Transparent Colored");
                        mat = new Material(shader);

                        // Save the material
                        AssetDatabase.CreateAsset(mat, matPath);
                        AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

                        // Load the material so it's usable
                        mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
                    }
                    else
                    {
                        AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
                    }

                    // Re-load the texture
                    tex = AssetDatabase.LoadAssetAtPath(texPath, typeof(Texture2D)) as Texture2D;

                    // Assign the texture
                    mat.mainTexture          = tex;
                    NGUISettings.fontTexture = tex;

                    uiFont.atlas    = null;
                    uiFont.material = mat;
                }
            }
            else
            {
                return;
            }
        }

        if (prefab != null)
        {
            // Update the prefab
            PrefabUtility.ReplacePrefab(go, prefab);
            DestroyImmediate(go);
            AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

            // Select the atlas
            go     = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
            uiFont = go.GetComponent <UIFont>();
        }

        if (uiFont != null)
        {
            NGUISettings.ambigiousFont = uiFont;
        }
        MarkAsChanged();
        Selection.activeGameObject = go;
    }
コード例 #29
0
    /// <summary>
    /// Draw the inspector widget.
    /// </summary>

    public override void OnInspectorGUI()
    {
        NGUIEditorTools.SetLabelWidth(80f);
        mAtlas = target as UIAtlas;

        UISpriteData sprite = (mAtlas != null) ? mAtlas.GetSprite(NGUISettings.selectedSprite) : null;

        GUILayout.Space(6f);

        if (mAtlas.replacement != null)
        {
            mType        = AtlasType.Reference;
            mReplacement = mAtlas.replacement;
        }

        GUILayout.BeginHorizontal();
        AtlasType after = (AtlasType)EditorGUILayout.EnumPopup("Atlas Type", mType);

        NGUIEditorTools.DrawPadding();
        GUILayout.EndHorizontal();

        if (mType != after)
        {
            if (after == AtlasType.Normal)
            {
                mType = AtlasType.Normal;
                OnSelectAtlas(null);
            }
            else
            {
                mType = AtlasType.Reference;
            }
        }

        if (mType == AtlasType.Reference)
        {
            ComponentSelector.Draw <UIAtlas>(mAtlas.replacement, OnSelectAtlas, true);

            GUILayout.Space(6f);
            EditorGUILayout.HelpBox("You can have one atlas simply point to " +
                                    "another one. This is useful if you want to be " +
                                    "able to quickly replace the contents of one " +
                                    "atlas with another one, for example for " +
                                    "swapping an SD atlas with an HD one, or " +
                                    "replacing an English atlas with a Chinese " +
                                    "one. All the sprites referencing this atlas " +
                                    "will update their references to the new one.", MessageType.Info);

            if (mReplacement != mAtlas && mAtlas.replacement != mReplacement)
            {
                NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
                mAtlas.replacement = mReplacement;
                NGUITools.SetDirty(mAtlas);
            }
            return;
        }

        //GUILayout.Space(6f);
        Material mat = EditorGUILayout.ObjectField("Material", mAtlas.spriteMaterial, typeof(Material), false) as Material;

        if (mAtlas.spriteMaterial != mat)
        {
            NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
            mAtlas.spriteMaterial = mat;

            // Ensure that this atlas has valid import settings
            if (mAtlas.texture != null)
            {
                NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
            }

            mAtlas.MarkAsChanged();
        }

        if (mat != null)
        {
            TextAsset ta = EditorGUILayout.ObjectField("TP Import", null, typeof(TextAsset), false) as TextAsset;

            if (ta != null)
            {
                // Ensure that this atlas has valid import settings
                if (mAtlas.texture != null)
                {
                    NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
                }

                NGUIEditorTools.RegisterUndo("Import Sprites", mAtlas);
                NGUIJson.LoadSpriteData(mAtlas, ta);
                if (sprite != null)
                {
                    sprite = mAtlas.GetSprite(sprite.name);
                }
                mAtlas.MarkAsChanged();
            }

            float pixelSize = EditorGUILayout.FloatField("Pixel Size", mAtlas.pixelSize, GUILayout.Width(120f));

            if (pixelSize != mAtlas.pixelSize)
            {
                NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
                mAtlas.pixelSize = pixelSize;
            }
        }

        if (mAtlas.spriteMaterial != null)
        {
            Color blueColor  = new Color(0f, 0.7f, 1f, 1f);
            Color greenColor = new Color(0.4f, 1f, 0f, 1f);

            if (sprite == null && mAtlas.spriteList.Count > 0)
            {
                string spriteName = NGUISettings.selectedSprite;
                if (!string.IsNullOrEmpty(spriteName))
                {
                    sprite = mAtlas.GetSprite(spriteName);
                }
                if (sprite == null)
                {
                    sprite = mAtlas.spriteList[0];
                }
            }

            if (sprite != null)
            {
                if (sprite == null)
                {
                    return;
                }

                Texture2D tex = mAtlas.spriteMaterial.mainTexture as Texture2D;

                if (tex != null)
                {
                    if (!NGUIEditorTools.DrawHeader("Sprite Details"))
                    {
                        return;
                    }

                    NGUIEditorTools.BeginContents();

                    GUILayout.Space(3f);
                    NGUIEditorTools.DrawAdvancedSpriteField(mAtlas, sprite.name, SelectSprite, true);
                    GUILayout.Space(6f);

                    GUI.changed = false;

                    GUI.backgroundColor = greenColor;
                    NGUIEditorTools.IntVector sizeA = NGUIEditorTools.IntPair("Dimensions", "X", "Y", sprite.x, sprite.y);
                    NGUIEditorTools.IntVector sizeB = NGUIEditorTools.IntPair(null, "Width", "Height", sprite.width, sprite.height);

                    EditorGUILayout.Separator();
                    GUI.backgroundColor = blueColor;
                    NGUIEditorTools.IntVector borderA = NGUIEditorTools.IntPair("Border", "Left", "Right", sprite.borderLeft, sprite.borderRight);
                    NGUIEditorTools.IntVector borderB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.borderBottom, sprite.borderTop);

                    EditorGUILayout.Separator();
                    GUI.backgroundColor = Color.white;
                    NGUIEditorTools.IntVector padA = NGUIEditorTools.IntPair("Padding", "Left", "Right", sprite.paddingLeft, sprite.paddingRight);
                    NGUIEditorTools.IntVector padB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.paddingBottom, sprite.paddingTop);

                    if (GUI.changed)
                    {
                        NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);

                        sprite.x      = sizeA.x;
                        sprite.y      = sizeA.y;
                        sprite.width  = sizeB.x;
                        sprite.height = sizeB.y;

                        sprite.paddingLeft   = padA.x;
                        sprite.paddingRight  = padA.y;
                        sprite.paddingBottom = padB.x;
                        sprite.paddingTop    = padB.y;

                        sprite.borderLeft   = borderA.x;
                        sprite.borderRight  = borderA.y;
                        sprite.borderBottom = borderB.x;
                        sprite.borderTop    = borderB.y;

                        MarkSpriteAsDirty();
                    }

                    GUILayout.Space(3f);

                    GUILayout.BeginHorizontal();

                    if (GUILayout.Button("Duplicate"))
                    {
                        UIAtlasMaker.SpriteEntry se = UIAtlasMaker.DuplicateSprite(mAtlas, sprite.name);
                        if (se != null)
                        {
                            NGUISettings.selectedSprite = se.name;
                        }
                    }

                    if (GUILayout.Button("Save As..."))
                    {
                        string path = EditorUtility.SaveFilePanel("Save As",
                                                                  NGUISettings.currentPath, sprite.name + ".png", "png");

                        if (!string.IsNullOrEmpty(path))
                        {
                            NGUISettings.currentPath = System.IO.Path.GetDirectoryName(path);
                            UIAtlasMaker.SpriteEntry se = UIAtlasMaker.ExtractSprite(mAtlas, sprite.name);

                            if (se != null)
                            {
                                byte[] bytes = se.tex.EncodeToPNG();
                                File.WriteAllBytes(path, bytes);
                                AssetDatabase.ImportAsset(path);
                                if (se.temporaryTexture)
                                {
                                    DestroyImmediate(se.tex);
                                }
                            }
                        }
                    }
                    if (GUILayout.Button("Save As All"))
                    {
                        string path = EditorUtility.SaveFolderPanel("Save As All",
                                                                    NGUISettings.currentPath, "");
                        if (!string.IsNullOrEmpty(path))
                        {
                            var list = mAtlas.spriteList;
                            foreach (var uiSpriteData in list)
                            {
                                var spName = uiSpriteData.name;
                                NGUISettings.currentPath = path;
                                UIAtlasMaker.SpriteEntry se = UIAtlasMaker.ExtractSprite(mAtlas, spName);
                                if (se != null)
                                {
                                    var    filePath = string.Format("{0}/{1}.png", path, spName);
                                    byte[] bytes    = se.tex.EncodeToPNG();
                                    File.WriteAllBytes(filePath, bytes);
                                    AssetDatabase.ImportAsset(filePath);
                                    if (se.temporaryTexture)
                                    {
                                        DestroyImmediate(se.tex);
                                    }
                                }
                            }
                        }
                    }
                    GUILayout.EndHorizontal();
                    NGUIEditorTools.EndContents();
                }

                if (NGUIEditorTools.DrawHeader("Modify"))
                {
                    NGUIEditorTools.BeginContents();

                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(20f);
                    EditorGUILayout.BeginVertical();

                    NGUISettings.backgroundColor = EditorGUILayout.ColorField("Background", NGUISettings.backgroundColor);

                    if (GUILayout.Button("Add a Shadow"))
                    {
                        AddShadow(sprite);
                    }
                    if (GUILayout.Button("Add a Soft Outline"))
                    {
                        AddOutline(sprite);
                    }

                    if (GUILayout.Button("Add a Transparent Border"))
                    {
                        AddTransparentBorder(sprite);
                    }
                    if (GUILayout.Button("Add a Clamped Border"))
                    {
                        AddClampedBorder(sprite);
                    }
                    if (GUILayout.Button("Add a Tiled Border"))
                    {
                        AddTiledBorder(sprite);
                    }
                    EditorGUI.BeginDisabledGroup(!sprite.hasBorder);
                    if (GUILayout.Button("Crop Border"))
                    {
                        CropBorder(sprite);
                    }
                    EditorGUI.EndDisabledGroup();

                    EditorGUILayout.EndVertical();
                    GUILayout.Space(20f);
                    EditorGUILayout.EndHorizontal();

                    NGUIEditorTools.EndContents();
                }

                if (NGUIEditorTools.previousSelection != null)
                {
                    GUILayout.Space(3f);
                    GUI.backgroundColor = Color.green;

                    if (GUILayout.Button("<< Return to " + NGUIEditorTools.previousSelection.name))
                    {
                        NGUIEditorTools.SelectPrevious();
                    }
                    GUI.backgroundColor = Color.white;
                }
            }
        }
    }
コード例 #30
0
    /// <summary>
    /// Draw the UI for this tool.
    /// </summary>

    void OnGUI()
    {
                #pragma warning disable 0618
        string prefabPath = "";
        string matPath    = "";

        if (UISettings.font != null && UISettings.font.name == UISettings.fontName)
        {
            prefabPath = AssetDatabase.GetAssetPath(UISettings.font.gameObject.GetInstanceID());
            if (UISettings.font.material != null)
            {
                matPath = AssetDatabase.GetAssetPath(UISettings.font.material.GetInstanceID());
            }
        }

        // Assume default values if needed
        if (string.IsNullOrEmpty(UISettings.fontName))
        {
            UISettings.fontName = "New Font";
        }
        if (string.IsNullOrEmpty(prefabPath))
        {
            prefabPath = NGUIEditorTools.GetSelectionFolder() + UISettings.fontName + ".prefab";
        }
        if (string.IsNullOrEmpty(matPath))
        {
            matPath = NGUIEditorTools.GetSelectionFolder() + UISettings.fontName + ".mat";
        }

        EditorGUIUtility.LookLikeControls(80f);

        NGUIEditorTools.DrawHeader("Input");

        UISettings.fontData    = EditorGUILayout.ObjectField("Font Data", UISettings.fontData, typeof(TextAsset), false) as TextAsset;
        UISettings.fontTexture = EditorGUILayout.ObjectField("Texture", UISettings.fontTexture, typeof(Texture2D), false) as Texture2D;

        // Draw the atlas selection only if we have the font data and texture specified, just to make it easier
        if (UISettings.fontData != null && UISettings.fontTexture != null)
        {
            NGUIEditorTools.DrawHeader("Output");

            GUILayout.BeginHorizontal();
            GUILayout.Label("Font Name", GUILayout.Width(76f));
            GUI.backgroundColor = Color.white;
            UISettings.fontName = GUILayout.TextField(UISettings.fontName);
            GUILayout.EndHorizontal();

            ComponentSelector.Draw <UIFont>("...or select", UISettings.font, OnSelectFont);
            ComponentSelector.Draw <UIAtlas>(UISettings.atlas, OnSelectAtlas);
        }
        NGUIEditorTools.DrawSeparator();

        // Helpful info
        if (UISettings.fontData == null)
        {
            GUILayout.Label(
                "The font creation mostly takes place outside\n" +
                "of Unity. You can use BMFont on Windows\n" +
                "or your choice of Glyph Designer or the\n" +
                "less expensive bmGlyph on the Mac.\n\n" +
                "Either of those tools will create a TXT for\n" +
                "you that you will drag & drop into the\n" +
                "field above.");
        }
        else if (UISettings.fontTexture == null)
        {
            GUILayout.Label(
                "When exporting your font, you should get\n" +
                "two files: the TXT, and the texture. Only\n" +
                "one texture can be used per font.");
        }
        else if (UISettings.atlas == null)
        {
            GUILayout.Label(
                "You can create a font that doesn't use a\n" +
                "texture atlas. This will mean that the text\n" +
                "labels using this font will generate an extra\n" +
                "draw call, and will need to be sorted by\n" +
                "adjusting the Z instead of the Depth.\n\n" +
                "If you do specify an atlas, the font's texture\n" +
                "will be added to it automatically.");

            NGUIEditorTools.DrawSeparator();

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUI.backgroundColor = Color.red;
            bool create = GUILayout.Button("Create a Font without an Atlas", GUILayout.Width(200f));
            GUI.backgroundColor = Color.white;
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            if (create)
            {
                GameObject go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;

                if (go == null || EditorUtility.DisplayDialog("Are you sure?", "Are you sure you want to replace the contents of the " +
                                                              UISettings.fontName + " font with the currently selected values? This action can't be undone.", "Yes", "No"))
                {
                    // Try to load the material
                    Material mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;

                    // If the material doesn't exist, create it
                    if (mat == null)
                    {
                        Shader shader = Shader.Find("Unlit/Transparent Colored");
                        mat = new Material(shader);

                        // Save the material
                        AssetDatabase.CreateAsset(mat, matPath);
                        AssetDatabase.Refresh();

                        // Load the material so it's usable
                        mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
                    }

                    mat.mainTexture = UISettings.fontTexture;

                    if (go == null || go.GetComponent <UIFont>() == null)
                    {
                        // Create a new prefab for the atlas
#if UNITY_3_4
                        Object prefab = EditorUtility.CreateEmptyPrefab(prefabPath);
#else
                        Object prefab = PrefabUtility.CreateEmptyPrefab(prefabPath);
#endif
                        // Create a new game object for the font
                        go = new GameObject(UISettings.fontName);
                        UISettings.font          = go.AddComponent <UIFont>();
                        UISettings.font.material = mat;
                        BMFontReader.Load(UISettings.font.bmFont, NGUITools.GetHierarchy(UISettings.font.gameObject), UISettings.fontData.bytes);

                        // Update the prefab
#if UNITY_3_4
                        EditorUtility.ReplacePrefab(go, prefab);
#else
                        PrefabUtility.ReplacePrefab(go, prefab);
#endif
                        DestroyImmediate(go);
                        AssetDatabase.Refresh();

                        // Select the atlas
                        go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
                    }

                    UISettings.font = go.GetComponent <UIFont>();
                    MarkAsChanged();
                }
            }
        }
        else
        {
            GameObject go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;

            bool create = false;

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();

            if (go != null)
            {
                if (go.GetComponent <UIFont>() != null)
                {
                    GUI.backgroundColor = Color.red;
                    create = GUILayout.Button("Replace the Font", GUILayout.Width(140f));
                }
                else
                {
                    GUI.backgroundColor = Color.grey;
                    GUILayout.Button("Rename Your Font", GUILayout.Width(140f));
                }
            }
            else
            {
                GUI.backgroundColor = Color.green;
                create = GUILayout.Button("Create the Font", GUILayout.Width(140f));
            }
            GUI.backgroundColor = Color.white;
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            if (create)
            {
                if (go == null || EditorUtility.DisplayDialog("Are you sure?", "Are you sure you want to replace the contents of the " +
                                                              UISettings.fontName + " font with the currently selected values? This action can't be undone.", "Yes", "No"))
                {
                    UIAtlasMaker.AddOrUpdate(UISettings.atlas, UISettings.fontTexture);

                    if (go == null || go.GetComponent <UIFont>() == null)
                    {
                        // Create a new prefab for the atlas
#if UNITY_3_4
                        Object prefab = EditorUtility.CreateEmptyPrefab(prefabPath);
#else
                        Object prefab = PrefabUtility.CreateEmptyPrefab(prefabPath);
#endif
                        // Create a new game object for the font
                        go = new GameObject(UISettings.fontName);
                        UISettings.font            = go.AddComponent <UIFont>();
                        UISettings.font.atlas      = UISettings.atlas;
                        UISettings.font.spriteName = UISettings.fontTexture.name;
                        BMFontReader.Load(UISettings.font.bmFont, NGUITools.GetHierarchy(UISettings.font.gameObject), UISettings.fontData.bytes);

                        // Update the prefab
#if UNITY_3_4
                        EditorUtility.ReplacePrefab(go, prefab);
#else
                        PrefabUtility.ReplacePrefab(go, prefab);
#endif
                        DestroyImmediate(go);
                        AssetDatabase.Refresh();

                        // Select the atlas
                        go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
                    }
                    else if (UISettings.fontData != null)
                    {
                        BMFontReader.Load(UISettings.font.bmFont, NGUITools.GetHierarchy(UISettings.font.gameObject), UISettings.fontData.bytes);
                        EditorUtility.SetDirty(UISettings.font);
                        UISettings.font.MarkAsDirty();
                    }

                    UISettings.font            = go.GetComponent <UIFont>();
                    UISettings.font.spriteName = UISettings.fontTexture.name;
                    UISettings.font.atlas      = UISettings.atlas;
                    MarkAsChanged();
                }
            }
        }
                #pragma warning restore 0618
    }
コード例 #31
0
ファイル: UIAtlasMaker.cs プロジェクト: willFuRoy/Unity
 void OnDisable()
 {
     instance = null;
 }
コード例 #32
0
	//
	private static void  UpdateSignalAtlas(UIAtlas atlas,List<string> files,bool search){
		if(atlas != null && files != null){
			/*
			if(atlas.texture.width >=2048 || atlas.texture.height >=2048){
				Debug.LogError("图集过大,请手动更新:"+atlas.name);
				return ;
			}
			*/
			List<UIAtlas.Sprite> sprites = atlas.spriteList;
			List<string> names = new List<string>();
			foreach(UIAtlas.Sprite sprite in sprites){
				//Debug.Log(sprite.name);
				names.Add(sprite.name);
			}

			List<Texture> textures = new List<Texture>();
			int i = 0;
			foreach(string filePath in files){
				if(names.Count == 0){
					Debug.Log("texture count:"+textures.Count+" find count:"+i+" search count:"+files.Count);
					Debug.Log("Process Atlas:"+atlas.name);
					break;
				}

				float process = (float)i/(float)files.Count;
				EditorUtility.DisplayProgressBar(
					"Progress Atlas:"+atlas.name,
					filePath,
					process);

				string name = Path.GetFileNameWithoutExtension(filePath);
				if(names.Contains(name)){
					Texture obj = AssetDatabase.LoadMainAssetAtPath(filePath) as Texture;
					if(isApprorateTexture(sprites,obj)){
						textures.Add(obj);
						names.Remove(name);
						//Debug.LogWarning(filePath);
						if(textures.Count >= 50){
							UIAtlasMaker.UpdateAtlasEX(atlas,textures);
							Resources.UnloadUnusedAssets();
							textures.Clear();
						}
					}
				}else{
					//Debug.Log(filePath);
				}
				i++;
			}
			
			EditorUtility.ClearProgressBar();
			foreach(string name in names){
				Debug.LogError("could not find:"+name + " of " + atlas.name+".please find the org texture");
			}
			
			if(textures.Count > 0){
				UIAtlasMaker.UpdateAtlasEX(atlas,textures);
				Resources.UnloadUnusedAssets();
				textures.Clear();	
			}
		 	/*
			if(!search){
				int lllcount = -1;
				if(textures.Count != 0 ){
					if(lllcount > 0){
						for(int m = 0;m<textures.Count;){
							UIAtlasMaker.UpdateAtlasEX(atlas,textures.GetRange(m,
								textures.Count - m >=lllcount?lllcount:textures.Count - m));
							m = m+lllcount;
							Debug.Log(m/lllcount);
							Resources.UnloadUnusedAssets();
						}
					}else{
						UIAtlasMaker.UpdateAtlasEX(atlas,textures);
						Resources.UnloadUnusedAssets();
					}
				}
			}
			*/	
		}
		
	}