using UnityEngine; using UnityEngine.UI; namespace UVC.Extension { /// /// Unity UI Text 컴포넌트에 대한 확장 메서드 모음 /// public static class TextEx { /// /// Text 컴포넌트에 텍스트를 설정하되, 주어진 영역을 초과할 경우 말줄임표(...)를 추가합니다. /// /// 대상 Text 컴포넌트 /// 표시할 텍스트 내용 /// /// /// // 사용 예시 /// Text myText = GetComponent(); /// myText.SetTextWithEllipsis("이 텍스트가 너무 길면 자동으로 줄여집니다..."); /// /// public static void SetTextWithEllipsis(this Text txt, string value) { // TextGenerator 생성 및 텍스트 컴포넌트의 설정값 가져오기 TextGenerator generator = new TextGenerator(); RectTransform rectTrans = txt.rectTransform; TextGenerationSettings settings = txt.GetGenerationSettings(rectTrans.rect.size); generator.Populate(value, settings); // 표시 가능한 문자 수 계산 int characterCountVisible = generator.characterCountVisible; string updatedText = value; // 텍스트가 표시 영역을 초과하는 경우 말줄임표 처리 if (value.Length > characterCountVisible && characterCountVisible >= 3) { updatedText = value.Substring(0, characterCountVisible - 3); updatedText += "..."; } // 결과 텍스트 설정 txt.text = updatedText; } /// /// 텍스트 컴포넌트의 내용을 지정된 최대 길이로 제한합니다. /// /// 대상 Text 컴포넌트 /// 표시할 텍스트 /// 최대 글자수 /// /// /// Text myText = GetComponent(); /// myText.SetTextWithMaxLength("긴 텍스트 내용입니다", 10); // "긴 텍스트 ..." /// /// public static void SetTextWithMaxLength(this Text txt, string value, int maxLength) { if (string.IsNullOrEmpty(value) || value.Length <= maxLength) { txt.text = value; return; } txt.text = value.Substring(0, maxLength - 3) + "..."; } /// /// 텍스트 컴포넌트에 숫자를 천 단위 구분자(,)와 함께 표시합니다. /// /// 대상 Text 컴포넌트 /// 표시할 숫자 /// /// /// Text scoreText = GetComponent(); /// scoreText.SetNumberWithCommas(1000000); // "1,000,000" 표시 /// /// public static void SetNumberWithCommas(this Text txt, int number) { txt.text = string.Format("{0:#,0}", number); } /// /// 텍스트가 표시 영역에 맞게 자동으로 폰트 크기를 조절합니다. /// /// 대상 Text 컴포넌트 /// 표시할 텍스트 /// 최소 폰트 크기 /// 최대 폰트 크기 /// /// /// Text titleText = GetComponent(); /// titleText.SetTextWithBestFit("제목 텍스트", 10, 30); /// /// public static void SetTextWithBestFit(this Text txt, string value, int minSize = 10, int maxSize = 40) { txt.text = value; txt.resizeTextForBestFit = true; txt.resizeTextMinSize = minSize; txt.resizeTextMaxSize = maxSize; } } }