NGUI 表情支持控件UIEmojiLabel,支持自適應多行多列

版權聲明:本文為Jumbo原創文章,采用[知識共享 署名-非商業性使用-禁止演繹 4.0 國際 許可協議],轉載前請保證理解此協議
原文出處:http://www.lxweimin.com/p/a604b3f1fce3

NGUI出來已久,使用范圍,場景越來越廣。本身在高版本NGUI也支持表情,但存在一些缺陷,例如:支持文字和表情顯示,但要求是必須文字和表情都需要在BMFont制作,對于文字量非常大的需求下,NGUI自帶的文本混合表情,就顯得力不從心。具體用過的同學,應該都知道的。

NGUI控件擴展,支持自適應多行多列表情
思路:
1、輸入文本表情,在文本處理的時候,處理表情字串,記錄位置
2、根據位置信息,得到文本在渲染時候的頂點位置,存在this.geometry.verts中
3、為什么位置要*4? 因為每個字串有4個頂點數據
4、把站位的emSpace ,位置賦給UISprite(顯示表情的控件)
5、所有的表情,通過表情管理器動態統一管理,不顯示時,回收

1、UIEmojiLabel

/*
 * Emoji Label @By Jumbo 2017/3/3
 * */

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Text;

public class UIEmojiLabel : UILabel {
    
    private  char emSpace = '\u2001';
    private List<GameObject> mEmojiList = new List<GameObject>();

    public UIAtlas emAtlas = null;
    protected override void OnStart()
    {
        base.OnStart();

//表情統一管理器,只初始化一次
        UIEmojiWrapper.Instance.Init(emAtlas);
    }

    //自動轉碼
    public override void OnFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
    {
        base.OnFill(verts, uvs, cols);


        //Test  測試代碼,正式使用,這里注釋掉,外面改變Label 的值
        string tx = "zhongz中國" + UIEmojiWrapper.Instance.GetConvertedString("1f61c") + UIEmojiWrapper.Instance.GetConvertedString("1f4fa") + UIEmojiWrapper.Instance.GetConvertedString("1f63f") + UIEmojiWrapper.Instance.GetConvertedString("1f607") + "國家回憶中心年內" + "sdfjsdlkj" + UIEmojiWrapper.Instance.GetConvertedString("1f63b") + "國家" + UIEmojiWrapper.Instance.GetConvertedString("1f467-1f3ff") + UIEmojiWrapper.Instance.GetConvertedString("1f450-1f4ff");// + "好行。天使good bye";
        text = tx;
///~測試代碼
        StartCoroutine(SetUITextThatHasEmoji(text));
    }


    private struct PosStringTuple
    {
        public int pos;
        public string emoji;

        public PosStringTuple(int p, string s)
        {
            this.pos = p;
            this.emoji = s;
        }
    }


    public IEnumerator SetUITextThatHasEmoji(string inputString)
    {
        List<PosStringTuple> emojiReplacements = new List<PosStringTuple>();
        StringBuilder sb = new StringBuilder();

        //先回收
        UIEmojiWrapper.Instance.PushEmoji(ref mEmojiList);
        int i = 0;
        while (i < inputString.Length)
        {
            string singleChar = inputString.Substring(i, 1);
            string doubleChar = "";
            string fourChar = "";

            if (i < (inputString.Length - 1))
            {
                doubleChar = inputString.Substring(i, 2);
            }

            if (i < (inputString.Length - 3))
            {
                fourChar = inputString.Substring(i, 4);
            }

            if (UIEmojiWrapper.Instance.HasEmoji(fourChar))
            {
                // Check 64 bit emojis first
                sb.Append(emSpace);
                emojiReplacements.Add(new PosStringTuple(sb.Length - 1, fourChar));
                i += 4;
            }
            else if (UIEmojiWrapper.Instance.HasEmoji(doubleChar))
            {
                // Then check 32 bit emojis
                sb.Append(emSpace);
                emojiReplacements.Add(new PosStringTuple(sb.Length - 1, doubleChar));
                i += 2;
            }
            else if (UIEmojiWrapper.Instance.HasEmoji(singleChar))
            {
                // Finally check 16 bit emojis
                sb.Append(emSpace);
                emojiReplacements.Add(new PosStringTuple(sb.Length - 1, singleChar));
                i++;
            }
            else
            {
                sb.Append(inputString[i]);
                i++;
            }
        }

        // Set text
        this.text = sb.ToString();

        yield return null;

      
        for (int j = 0; j < emojiReplacements.Count; j++)
        {
            int emojiIndex = emojiReplacements[j].pos;
            //表情替換,計算位置,大小
            GameObject go = UIEmojiWrapper.Instance.PopEmoji();
            if (go != null)
            {
                UISprite spt = go.GetComponent<UISprite>();
                if (spt != null)
                {
                    string emoji = UIEmojiWrapper.Instance.GetEmoji(emojiReplacements[j].emoji);
                    if (!string.IsNullOrEmpty(emoji))
                    {
                        spt.name = emoji;
                        spt.spriteName = emoji;
                    }
//mPrintedSize 父類權限私有,可以改為子類可范圍的保護的權限,渲染的字體大小變化,來改變UISprite的大小
                    spt.width = this.mPrintedSize;
                    spt.height = this.mPrintedSize;
                    spt.transform.parent = this.transform;
                    spt.transform.localScale = Vector3.one;
                    spt.transform.localPosition = new Vector3(this.geometry.verts[emojiIndex * 4].x + spt.width / 2, this.geometry.verts[emojiIndex * 4].y + spt.height / 2);
                }

                mEmojiList.Add(go);
            }
        }
}

}

2、UIEmojiLabelInspector 編輯器監視

/*
 * Emoji Label Inspector @By Jumbo 2017/3/3
 * */

#if !UNITY_3_5 && !UNITY_FLASH
#define DYNAMIC_FONT
#endif

using UnityEngine;
using UnityEditor;

/// <summary>
/// Inspector class used to edit UILabels.
/// </summary>

[CanEditMultipleObjects]
#if UNITY_3_5
[CustomEditor(typeof(UILabel))]
#else
[CustomEditor(typeof(UILabel), true)]
#endif
public class UIEmojiLabelInspector : UILabelInspector
{
    
        
    /// <summary>
    /// Draw the label's properties.
    /// </summary>

    protected override bool ShouldDrawProperties ()
    {
        bool isValid = base.ShouldDrawProperties();

        EditorGUI.BeginDisabledGroup(!isValid);
        NGUIEditorTools.DrawProperty("Atlas", serializedObject, "emAtlas");//表情所在的圖集Atlas
        EditorGUI.EndDisabledGroup();
        return isValid;
    }
}

3、UIEmojiWrapper 表情統一管理器

/*
 * Emoji Wrapper @By Jumbo 2017/3/3
 * */

using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

class UIEmojiWrapper
{
    private bool hasAtlas = false;
    private UIAtlas mAtlas;
    private GameObject emojiPrefab;
    private Dictionary<string, string> emojiName = new Dictionary<string, string>();
    private Queue<GameObject> freeSprite = new Queue<GameObject>();
    
    private List<GameObject> usedSprite = new List<GameObject>();

    private Vector3 OutOffScreen = new Vector3(10000f, 10000f, 10000f);

    private static UIEmojiWrapper sInstance;
    public static UIEmojiWrapper Instance
    {
        get
        {
            if(sInstance == null)
            {
                sInstance = new UIEmojiWrapper();
            }
            
            return sInstance;
        }
    }
    
    public void Init(UIAtlas atlas)
    {
        if (!hasAtlas)
        {
            if (atlas == null)
            {
                LogUtil.LogError(WXLogTag.LogTag_UI, "[UIEmojiWrapper Atlas is null]");
                return;
            }
            mAtlas = atlas;
            //預分配
            for (int i = 0, cnt = mAtlas.spriteList.Count; i < cnt; i++)
            {
                emojiName.Add(GetConvertedString(mAtlas.spriteList[i].name), mAtlas.spriteList[i].name);
            }

            emojiPrefab = new GameObject();
            UISprite spt = emojiPrefab.AddComponent<UISprite>();
            if (spt != null)
            {
                spt.transform.localPosition = OutOffScreen;
                spt.name = "emojiPrefab";

            }

            hasAtlas = true;
        }
        
    }

    public string GetConvertedString(string inputString)
    {
        string[] converted = inputString.Split('-');
        for (int j = 0; j < converted.Length; j++)
        {
            converted[j] = char.ConvertFromUtf32(Convert.ToInt32(converted[j], 16));
        }
        return string.Join(string.Empty, converted);
    }

    public string GetEmoji(string encode)
    {
        string em;

        if(emojiName.TryGetValue(encode, out em))
        {
            return em;
        }

        return null;
    }
    public bool HasEmoji(string key)
    {
        return emojiName.ContainsKey(key);
    }

     public void OnPostFill (UIWidget widget, int bufferOffset, BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
     {
         if (widget != null)
         {
             if(!widget.isVisible)
             {
                 UISprite spt = widget as UISprite;
                 if (spt != null)
                 {
                     PushEmoji(spt.gameObject);
                 }
             }
         }
     }

    public GameObject PopEmoji()
    {
        if (freeSprite.Count <= 0)
        {
            if (emojiPrefab == null)
                return null;

            GameObject tran = GameObject.Instantiate(emojiPrefab) as GameObject;
            UISprite spt = tran.GetComponent<UISprite>();
            if (spt != null)
            {
                spt.atlas = mAtlas;
                spt.hideIfOffScreen = true;
                spt.onPostFill += OnPostFill;
            }
                

            freeSprite.Enqueue(tran);
        }

        GameObject sptRet = freeSprite.Dequeue();
        
        if (sptRet != null)
        {
            usedSprite.Add(sptRet);
        }

        return sptRet;

    }


    public void PushEmoji(GameObject spt)
    {
        spt.transform.localPosition = OutOffScreen;
        spt.transform.parent = null;
        freeSprite.Enqueue(spt);
    }

    public void PushEmoji (ref List<GameObject> list)
    {
        for (int i = 0, cnt = list.Count; i < cnt; i++)
        {
            PushEmoji(list[i]);
        }

        list.Clear();
    }
}

有更好的方案,不吝賜教~~

【原創】轉摘請保留原文鏈接http://www.lxweimin.com/p/a604b3f1fce3
Demo效果:

文本表情混排效果

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,250評論 6 530
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 97,923評論 3 413
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,041評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,475評論 1 308
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,253評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,801評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,882評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,023評論 0 285
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,530評論 1 331
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,494評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,639評論 1 366
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,177評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,890評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,289評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,552評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,242評論 3 389
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,626評論 2 370

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,574評論 25 707
  • 1、在vm菜單欄選擇Player->管理->安裝VMware Tools 2、終端運行不帶參數的mount命令檢查...
    冰鎮果汁加點糖閱讀 262評論 0 0
  • 星期天我們很早起床去新昌。大巴車上我們表演了很多節目。節目種類有很多很多,有古詩有歌曲。我們坐在大巴車上互...
    終點是你閱讀 530評論 0 0
  • 上班這些年以來,為了管紀律,對于學生的獎懲也有很多了,現在看過去,發現有成功的,也有失敗的。成功源于隨心,失敗也源...
    葉輝閱讀 258評論 4 0
  • 感恩天地萬物滋養生命,感恩空氣,水,食物滋養身體健康,感恩歷代宗親傳承血脈,感恩父母養育之恩,感恩兄弟姐妹互幫互助...
    銀菠蘿蜜閱讀 91評論 0 0