[英]Find Max Line Count for Unity UI.Text
我正在嘗試確定將VerticalOverflow
設置為truncate
的UI.Text
的最大行數,以便以后可以使用行數。 到目前為止,我提出了以下代碼,這顯然是不切實際的,甚至可能是危險的:
/// <summary>
/// Returns the max visible line count of a UI.Text component. The text's vertical
/// overflow must be set to truncate or this method will return 0.
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static int GetMaxLineCount(Text text)
{
if (text == null || text.verticalOverflow != VerticalWrapMode.Truncate) return 0;
var textBackup = text.text;
var lineCount = 0;
text.text = "";
while (true)
{
text.text += "\n";
Canvas.ForceUpdateCanvases();
var nextLineCount = text.cachedTextGenerator.lineCount;
if (lineCount == nextLineCount) break;
lineCount = nextLineCount;
}
text.text = textBackup;
return lineCount;
}
有沒有更好的方法來(預先)確定UI.Text組件的最大行數(在底部截斷文本之前)?
您可以嘗試使用類似這樣的東西
TextGenerator textGenenerator = new TextGenerator(); TextGenerationSettings generationSettings = text.GetGenerationSettings(text.rectTransform.rect.size); float height = textGenenerator.GetPreferredHeight(newText, generationSettings);
您可以在這里閱讀有關它的更多信息https://docs.unity3d.com/ScriptReference/TextGenerator.html
---與您的代碼有關的注釋-
您調用Canvas.ForceUpdateCanvases(),這將導致大量調用,僅更新一個Text並在運行該代碼時檢查器設置不正確,如果Text允許無限行,則可能會陷入無限循環。
感謝@Neven向我指出正確的方向! TextGenerator
可用於計算背景中的最大行數。 好處是Canvas.ForceUpdateCanvases()
不再需要調用,並且原始Text不會更改。 它仍然需要一個循環來找出最大行數,但是比我的第一種方法要好得多...
public static int GetMaxLineCount(Text text)
{
var textGenerator = new TextGenerator();
var generationSettings = text.GetGenerationSettings(text.rectTransform.rect.size);
var lineCount = 0;
var s = new StringBuilder();
while (true)
{
s.Append("\n");
textGenerator.Populate(s.ToString(), generationSettings);
var nextLineCount = textGenerator.lineCount;
if (lineCount == nextLineCount) break;
lineCount = nextLineCount;
}
return lineCount;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.