unity英文自动添加连词符“-”

文章讲述了如何在Unity中解决Text组件换行导致的文字美观度问题,通过在单词中间添加连字符并检测宽度来实现文本自动换行且保持边缘对齐。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

unity自带的text组件当需要换行时会自动把整个单词都移动到下一行,比如下面的情况:
请添加图片描述
但当我们有一大段文字的时候这种换行规则会导致文字的右边不能完美的与边缘对齐,会空出来一大片,导致美观度降低。
在这里插入图片描述
所以采用在单词中间进行截断并且添加连词符(-)的方式来避免这种情况的产生。
在这里插入图片描述

请添加图片描述

C#代码:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UITest : MonoBehaviour
{
    private Text lab;
    private void Awake()
    {
        lab = transform.Find("Text").GetComponent<Text>();
    }

    private void Start()
    {
        string temp = "lua integration state where scale in projects lua integration state where scale in projects lua integration state where scale in projects lua integration state where scale in projectslua integration state where scale in projects";
        temp = temp.Replace(" ", "\u00A0");
        lab.text = temp;
    }

    private void Update()
    {
        string temp = "lua integration state where scale in projects lua integration state where scale in projects lua integration state where scale in projects lua integration state where scale in projectslua integration state where scale in projects";
        temp = temp.Replace(" ", "\u00A0");
        lab.text = temp;
        WrapTextWithHyphen(lab, temp);
    }

    public void WrapTextWithHyphen(Text textComponent, string str)
    {
        string originalText = str;
        string[] words = originalText.Split('\u00A0');

        float textWidth = textComponent.rectTransform.rect.width;
        string wrappedText = "";
        string line = "";
        for (int i = 0; i < words.Length; i++)
        {
            string word = words[i];
            string spaceLine = line + "\u00A0";
            if (GetTextPreferredWidth(textComponent,spaceLine + word) > textWidth)
            {
                for (int j = 1; j <= word.Length; j++)
                {
                    string substring = word.Substring(0, j);
                    if (GetTextPreferredWidth(textComponent,spaceLine + substring + "-") > textWidth)
                    {
                        //防止刚好是空格+单个字母+"-"超行的情况,这个时候直接把这个单词放到下一行
                        if (j == 1)
                        {
                            wrappedText += line + " ";
                            line = word;
                        }
                        else
                        {
                            string tempStr = spaceLine + word.Substring(0, j - 1) + "-\n";
                            wrappedText += tempStr;
                            line = word.Substring(j - 1);
                        }
                        break;
                    }
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(line))
                {
                    line += "\u00A0"; 
                }
                line += word;
            }
        }

        wrappedText += line;
        textComponent.supportRichText = true;
        textComponent.text = wrappedText;
    }

    public float GetTextPreferredWidth(Text textComp, string content)
    {
        return textComp.cachedTextGenerator.GetPreferredWidth(content,
            textComp.GetGenerationSettings(textComp.rectTransform.rect.size));
    }
}

lua代码:

其主要是利用GetGenerationSettings接口获取字符串的渲染宽度从而自动自动添加连字符,lua 5.1本版需要下载utf8扩展库,其他lua5.3版本自带utf8库,但接口名字有所不同

-- hyphen_util.txt --------------------------------------------------
-- author:
-- date: 
-- ver:  
-- desc:    自动添加连词符
-------------------------------------------------------------------

local event = require "event"
local util = require "util"
local log = require "log"
local lang = require "lang"
local utf8 = require "utf8"
local tostring = tostring
local ipairs = ipairs
local require = require
local dump = dump
local print = print
local string = string
local tonumber = tonumber
local type = type
local typeof = typeof

module("hyphen_util")

local isEnable = true  --启用功能

--下面这些字符前面和后面不会添加连词符
local noAppendHyphenCharacter =
{
    ["-"]="-",
    ["."]=".",
    [","]=",",
    ["。"]="。",
    [","]=",",
    ["{"]="{",
    ["}"]="}",
    ["("]="(",
    [")"]=")",
    ["("]="(",
    [")"]=")",
    ["["]="[",
    ["]"]="]",
    ["|"]="|",
    ["&"]="&",
    ["*"]="*",
    ["/"]="/",
    ["\\"]="\\",
    ["#"]="#",
    ["%"]="%",
    ["~"]="~",
    ["、"]="、",
    [":"]=":",
    [";"]=";",
    ["?"]="?",
    ["?"]="?",
    ["!"]="!",
    ["`"]="`",
    ["\'"]="\'",
    ["\""]="\"",
    ["$"]="$",
    ["_"]="_",
    ["0"]="0",
    ["1"]="1",
    ["2"]="2",
    ["3"]="3",
    ["4"]="4",
    ["5"]="5",
    ["6"]="6",
    ["7"]="7",
    ["8"]="8",
    ["9"]="9",
}

---自动添加连词符,添加连词符需要关闭bestfit、开启富文本显示,只能给needAppendHyphenLanguage列表里面的语言添加连词符
---@param textComponent text text组件
---@param str string
---@param delayTime double 延迟时间,部分text在赋值之后需要短暂延迟才能计算text组件的宽度
function AutoAppendHyphen(textComponent, str, delayTime)
    local func = function()
        if not isEnable then
            return
        end
        if IsNullOrEmpty(str) then
            str = textComponent.text
            if str == "" then
                return
            end
        end
        textComponent.resizeTextForBestFit = false
        textComponent.supportRichText = true
        textComponent.text = GetAppendHyphenStr(textComponent, str)
    end

    if delayTime then
        util.DelayCallOnce(delayTime, func)   --需要自己实现延迟功能
    else
        func()
    end
end

---返回添加了连词符的文本
---@param textComponent text text组件
---@param str string
---@return string 返回添加了连词符的文本
function GetAppendHyphenStr(textComponent, str)
    if not isEnable then
        return str
    end

    if IsNullOrEmpty(str) then
        str = textComponent.text
        if str == "" then
            return str
        end
    end

    local separator = " "
    if string.find(str, " ") then
        separator = " "
    end

    local words = string.split(str, separator)   --按照单词进行分割
    local textWidth = textComponent.rectTransform.rect.width     --获得当前的文本框宽度
    local line = ""
    local wrappedText = ""
    for _, word in ipairs(words) do
        local spaceLine = line .. separator
        if GetTextPreferredWidth(textComponent, spaceLine .. word) > textWidth then
            local substring = ""                --截断的单词
            local lastSubString = ""            --上一个截断单词
            local isFind = false                --是都找到了断行的位置
            local leaveStr = ""                 --剩余的字符串
            local oldChar                       --上一个字符
            for pos, char in utf8.codes(word) do
                substring = substring .. char
                if not isFind and GetTextPreferredWidth(textComponent,spaceLine .. substring .. "-") > textWidth then
                    --防止刚好是空格+单个字母+"-"超行的情况,这个时候直接把这个单词放到下一行
                    if not oldChar then
                        wrappedText = wrappedText .. line  .. "\n"
                        line = word
                        break
                    else
                        wrappedText = wrappedText .. spaceLine .. lastSubString
                        if noAppendHyphenCharacter[char] or noAppendHyphenCharacter[oldChar] then   --防止出现连续两个换行符的情况
                            wrappedText = wrappedText .. "\n"
                        else
                            wrappedText = wrappedText .. "-\n"
                        end
                        --wrappedText = wrappedText .. spaceLine .. lastSubString .. "-\n"
                        isFind = true
                    end
                end
                if isFind then
                    leaveStr = leaveStr .. char
                end
                oldChar = char
                lastSubString = substring
            end
            if not IsNullOrEmpty(leaveStr) then
                line = leaveStr
            end
        else
            if not IsNullOrEmpty(line) then
                line = line .. separator
            end
            line = line .. word
        end
    end
    wrappedText = wrappedText .. line
    return wrappedText
end

---计算text组件文本的宽度
function GetTextPreferredWidth(textComponent, str)
    return textComponent.cachedTextGenerator:GetPreferredWidth(str, textComponent:GetGenerationSettings(textComponent.rectTransform.rect.size))
end

function SetEnable(state)
    isEnable = state
end

function IsNullOrEmpty(str)
    return (not str) or str == ""
end

这里我提供C#语言的脚本和lua语言的脚本,请猛戳以下链接:
https://github.com/momohola/Unity-hyphen_util

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值