-->

分類

2017年4月23日 星期日

Unity UGUI text underline

reference


using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class TextUnderline : MonoBehaviour {
 //Text that draws underline
 public Text underline;

 /*
  refText: Text that its text content will be underlined
  clear: clear underline
  underlineVerticalOffsetScale: control distance between refText and underline
 
  sample hierarchy structure:

  refText(components: Text)
   underline(components: Text, TextUnderline)   
 */
 public void setup(Text refText, bool clear = false, float underlineVerticalOffsetScale = 1.0f)
 {
  if(clear)
  {
   underline.text = "";
   return;
  }
  RectTransform rt = underline.GetComponent();
  RectTransform refRT = refText.GetComponent();

  underline.font = refText.font;
  underline.fontSize = refText.fontSize;
  //underline.fontStyle = refText.fontStyle;
  underline.color = refText.color;
  underline.text = "_";

  rt.localScale = refRT.localScale;
  float refHeight = refText.preferredHeight;

  float perlineWidth = underline.preferredWidth * rt.localScale.x;
  Debug.Log(perlineWidth);

  float refWidth = refText.preferredWidth;
  int lineCount = (int)Mathf.Round(refWidth / perlineWidth);
  Debug.Log(lineCount);
  for (int i = 1; i < lineCount; i++)
  {
   underline.text += "_";
  }

  float selfHeight = underline.preferredHeight;
  rt.anchoredPosition = new Vector2(0.0f, -(refHeight + selfHeight) * underlineVerticalOffsetScale);
 }
}








沒有留言:

張貼留言