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

本文最后更新于 2024年5月26日 下午

unity自带的text组件当需要换行时会自动把整个单词都移动到下一行,比如下面的情况:

请添加图片描述

但当我们有一大段文字的时候这种换行规则会导致文字的右边不能完美的与边缘对齐,会空出来一大片,导致美观度降低。

在这里插入图片描述

所以采用在单词中间进行截断并且添加连词符(-)的方式来避免这种情况的产生。

在这里插入图片描述

请添加图片描述

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

C#代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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代码:(lua 的utf8库点击下面的链接下载)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
-- 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

Github链接:
https://github.com/momohola/Unity-hyphen_util


Unity英文自动添加连词符“-”
http://example.com/2024/05/26/Unity-hyphen/
作者
莫予
发布于
2024年5月26日
许可协议