我们在项目研发中经常会遇到实时改变文字框大小的需求,大面积使用自适应组件对游戏是一个负担,如果优化这个需求呢,其实Text中有一个preferred属性,可以让开发者知道Text渲染这些文字需要的宽度或者高度。
以下贴出一个封装函数,是lua写的。
--传入一个Text组件,type是获取高或者宽,自己决定设置什么。
--这里是直接把Text组件设置为刚好渲染出框内文字的宽或者高。
local function SetTextSize(text, type)
local RT = UIUtil.FindRectTransform(text.transform)
if type == 1 then
local width = text.preferredWidth
if text.text == "" then
width = 0
end
RT.sizeDelta = Vector2.New(width, RT.rect.height)
elseif type == 2 then
local height = text.preferredHeight
if text.text == "" then
height = 0
end
RT.sizeDelta = Vector2.New(RT.rect.width, height)
end
end