zoukankan      html  css  js  c++  java
  • Unity UGUI --- Text组件预先获取文本的宽度和高度

    转自:https://blog.csdn.net/u010180140/article/details/104049958

    原作者是用lua写的。明白用什么接口就好,什么语言不重要。

    给定文本内容给Text组建,预先知道Text占用的宽高

    利用TextGenerator,TextGenerationSettings可以提前知道Text占用的宽高

    function UIUtil.GetTextPreferredWidthAndHeight(cotent,fontSize)
        local font = ResourcesManager.GetAsset("font")
        local textGenerator = TextGenerator()
        local setting = TextGenerationSettings()
        setting.font = font
        setting.fontSize = fontSize
        setting.lineSpacing = 1
        setting.scaleFactor = 1
        setting.verticalOverflow = VerticalWrapMode.Overflow
        setting.horizontalOverflow = HorizontalWrapMode.Overflow
        
        local width = textGenerator:GetPreferredWidth(content,setting)
        local height = textGenerator:GetPreferredHeight(content,setting)
        
        return width,height
    end

    预先知道Text占用的宽高的作用

    (1)开始知道了Text占用的宽,可以预先做好换行处理

    (1)开始知道了Text占用的宽,可以预先做好字符串的处理,例如在聊天系统里面的最精联系人一栏会有最近联系人的头像下会有最新的一条聊天信息,如果最新的那条信息超出了我们给定的宽度就要做截断出来,超出来的字符串用“…”替换

    //预先获取限制宽度的字符串加上“…”结尾

    function UIUtil.GetLimitWidthClippedStr(str,fontSize,limitWidth)
        local charArr = StringUtil.StringToArray(str)
        local len = #charArr
        local ret = ""
        local retList = {}
        local line = 0
        for i = 0,len do
            local curStr = charArr[i]
            local width = UIUtil.GetTextPreferredWidthAndHeight(curStr,fontSize)
            line = line + width
            retList[#retList + 1] = curStr
            if line >= limitWidth then
                retList[#retList + 1] = "..."
                break
            end
        end
        ret = table.concat(retList,"")
        return ret
    end
  • 相关阅读:
    VMware 克隆一个虚拟机(win7)
    HDU 5695 Gym Class (拓扑排序、贪心、优先队列)
    HDU2647 Reward (拓扑排序、反向建图)
    HDU 3342 Legal or Not (拓扑排序、有向图是否存在环)
    Vue框架简介及简单使用
    Linux文件常用指令
    Linux系统相关命令
    Linux关机指令详解
    linux目录结构
    Linux用户相关命令
  • 原文地址:https://www.cnblogs.com/kuluodisi/p/13787824.html
Copyright © 2011-2022 走看看