NGUI 的原始版本是不支持英文单词换行的,他的判断是针对一个一个字符的。但是现在我们游戏有这个需求,就是当换行的位置是一个单词的时候,就把这个单词放到下一行显示。如下:
**修改前:this is ngui font br
eak
修改后:this is ngui font
break**
查阅ngui代码后发现,可以找到UIFont这个类有个 WrapText 函数 ,该函数的作用是给一个string 使用ngui的规则进行wrap。其中如果使用者使用了行宽(max width)这个 这个参数后,当字符超过了行宽就会换行了(比如:使用前的显示)。
所以我们就要在这个地方进行设置
int offsetSpaceIdx = 0;
public string WrapText(string text, float maxWidth, int maxLineCount, bool encoding, SymbolStyle symbolStyle)
{
// 第① :重置空格的位置
offsetSpaceIdx = 0;
// 第① end
// Run through all characters
for (; offset < textLength; ++offset)
{
char ch = text[offset];
// New line character -- start a new line
if (ch == '\n')
{
if (!multiline || lineCount == maxLineCount) break;
remainingWidth = lineWidth;
// Add the previous word to the final string
if (start < offset) sb.Append(text.Substring(start, offset - start + 1));
else sb.Append(ch);
lineIsEmpty = true;
++lineCount;
start = offset + 1;
previousChar = 0;
continue;
}
remainingWidth -= glyphWidth;
// 第② :记录空格的位置
#if Language_en
if(text[offset]==' '){
offsetSpaceIdx = offset;
}
#endif
// 第② end
// Doesn't fit?
if (remainingWidth < 0)
{
// 第③ :在换行的位置检测是否当前的字符是在一个单词内部
#if Language_en
if(offset < (textLength-1) && offsetSpaceIdx > start){
if(text[offset+1]!=' '){
offset = offsetSpaceIdx;
}else{
offset++;
}
}
#endif
// 第③ end
// Can't start a new line
if (lineIsEmpty || !multiline || lineCount == maxLineCount)
{
// This is the first word on the line -- add it up to the character that fits
sb.Append(text.Substring(start, Mathf.Max(0, offset - start)));
if (!multiline || lineCount == maxLineCount)
{
start = offset;
break;
}
EndLine(ref sb);
// Start a brand-new line
lineIsEmpty = true;
++lineCount;
if (ch == ' ')
{
start = offset + 1;
remainingWidth = lineWidth;
}
else
{
start = offset;
remainingWidth = lineWidth - glyphWidth;
}
previousChar = 0;
}
else
{
// Skip all spaces before the word
while (start < textLength && text[start] == ' ') ++start;
// Revert the position to the beginning of the word and reset the line
lineIsEmpty = true;
remainingWidth = lineWidth;
offset = start - 1;
previousChar = 0;
if (!multiline || lineCount == maxLineCount) break;
++lineCount;
EndLine(ref sb);
continue;
}
}
else previousChar = ch;
// Advance the offset past the symbol
if (!dynamic && symbol != null)
{
offset += symbol.length - 1;
previousChar = 0;
}
}
if (start < offset) sb.Append(text.Substring(start, offset - start));
return sb.ToString();
}
原始代码被大部分删减了,留下的都是该功能具体要被解释的地方,具体留意
第①,②,③ 的注释部分。
如有疑问请留言