其实本质是通过 .characterCountVisible 参数来获取显示出来的字符串长度,和实际要显示的文字字符串长度的比较,超过长度的话,最后的字符替换成“...”
需要注意一点,因为编码方式的不同,在使用 UTF-8 字符编码的情况下,一个中文字符一般占 3 个字节。实际上“测试文本”的string.len()结果是12,但是 .characterCountVisible取出来的结果是4.所以需要进行一次转换
function TasksTopTipsView:SetTextWithEllipsis(text, rect, value)
local generator = CS.UnityEngine.TextGenerator()
local settings = text:GetGenerationSettings(rect.size)
generator:Populate(value, settings)
local characterCountVisible = generator.characterCountVisible
if string.utf8len(value) ~= string.len(value) then
characterCountVisible = characterCountVisible*3
end
if string.len(value) > characterCountVisible then
text.text = string.sub(value, 0, characterCountVisible - 3) .. "..."
else
text.text = value
end
end
--计算 UTF8 字符串的长度,每一个中文算一个字符
function string.utf8len(input)
local len = string.len(input)
local left = len
local cnt = 0
local arr = {0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc}
while left ~= 0 do
local tmp = string.byte(input, -left)
local i = #arr
while arr[i] do
if tmp >= arr[i] then
left = left - i
break
end
i = i - 1
end
cnt = cnt + 1
end
return cnt
end