using System.Collections; using System.Collections.Generic; using Module.Log; using UnityEngine; using UnityEngine.UI; [ExecuteInEditMode] public class UIImgText : MonoBehaviour { public UIImgFont _ImgFont; public TextAnchor _TextAnchor = TextAnchor.UpperLeft; protected string _text = ""; [SerializeField] public string text { get { return _text; } set { _text = value; ShowImage(_text); } } public RectTransform _CharRoot; public bool _ResizeChatRoot = true; protected void InitCharRoot() { if (_CharRoot != null) return; var charRoot = new GameObject("CharRoot"); var horizon = charRoot.AddComponent(); horizon.childAlignment = _TextAnchor; horizon.childForceExpandHeight = false; horizon.childForceExpandWidth = false; var layoutElement = charRoot.AddComponent(); layoutElement.ignoreLayout = true; _CharRoot = charRoot.GetComponent(); _CharRoot.SetParent(transform); _CharRoot.sizeDelta = new Vector2(0, _CharRoot.sizeDelta.y); _CharRoot.localPosition = Vector3.zero; _CharRoot.localRotation = Quaternion.Euler(Vector3.zero); _CharRoot.localScale = Vector3.one; _CharRoot.sizeDelta = GetComponent().sizeDelta; } public void SetCharRootAlig(TextAnchor alig) { if (_CharRoot == null) return; var horizon = _CharRoot.gameObject.GetComponent(); if (horizon == null) return; horizon.childAlignment = alig; } #region protected Stack _IdleImgs = new Stack(); protected Image PopIdleImage() { InitCharRoot(); if (_IdleImgs == null || _IdleImgs.Count == 0) { var imageGO = new GameObject("charImg"); var image = imageGO.AddComponent(); imageGO.transform.SetParent(_CharRoot); imageGO.transform.localPosition = Vector2.zero; imageGO.transform.localRotation = Quaternion.Euler(Vector3.zero); imageGO.transform.localScale = Vector3.one; image.raycastTarget = false; image.gameObject.SetActive(true); return image; } else { var image = _IdleImgs.Pop(); image.gameObject.SetActive(true); return image; } } protected List _CharImages = new List(); protected void ClearImage() { for (int i = 0; i < _CharImages.Count; ++i) { _CharImages[i].gameObject.SetActive(false); _IdleImgs.Push(_CharImages[i]); } if (_CharRoot != null && _ResizeChatRoot) { _CharRoot.sizeDelta = new Vector2(0, _CharRoot.sizeDelta.y); } _CharImages.Clear(); } protected void ShowImage(string text) { ClearImage(); _ImgFont.InitChars(); for (int i = 0; i < text.Length; ++i) { if (!_ImgFont._DictImgChars.ContainsKey(text[i])) { LogModule.ErrorLog(string.Format(" {0} No Img Char :{1}" ,text, text[i])); continue; } var image = PopIdleImage(); var charImg = _ImgFont._DictImgChars[text[i]]; image.sprite = charImg._Image; image.rectTransform.sizeDelta = new Vector2(charImg._CharWidth, charImg._CharHeight); image.rectTransform.SetAsLastSibling(); if (_ResizeChatRoot) { _CharRoot.sizeDelta = new Vector2(_CharRoot.sizeDelta.x + charImg._CharWidth, _CharRoot.sizeDelta.y); } _CharImages.Add(image); } } #endregion }