南锋

南奔万里空,脱死锋镝余

Automatic Line Wrapping for Label Text in Cocos2dx-Lua

Development Environment: Cocos2dx 3.17
Development Language: Lua
During development, we often encounter situations where a string is too long and exceeds the display area. In such cases, we can set the Label to automatically wrap text.

Code:

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
function FunSetLinefeed( strText, nLineWidth )  -- Text, line width
-- Read each character, determine if it's Chinese or English, and record its size
local nStep = 1
local index = 1
local ltabTextSize = {}
while true do
c = string.sub(strText, nStep, nStep)
b = string.byte(c)

if b > 128 then
ltabTextSize[index] = 3
nStep = nStep + 3
index = index + 1
else
ltabTextSize[index] = 1
nStep = nStep + 1
index = index + 1
end

if nStep > #strText then
break
end
end

-- Group characters according to the specified line width
local nLineCount = 1
local nBeginPos = 1
local lptrCurText = nil
local ltabText = {}
local nCurSize = 0
for i = 1, index - 1 do
nCurSize = nCurSize + ltabTextSize[i]
if nCurSize > nLineWidth and nLineCount < math.ceil(#strText / nLineWidth) then
nCurSize = nCurSize - ltabTextSize[i]
ltabText[nLineCount] = string.sub(strText, nBeginPos, nBeginPos + nCurSize - 1)
nBeginPos = nBeginPos + nCurSize
nCurSize = ltabTextSize[i]
nLineCount = nLineCount + 1
end
if nLineCount == math.ceil(#strText / nLineWidth) then
ltabText[nLineCount] = string.sub(strText, nBeginPos, #strText)
end
end

-- Combine the text lines
for i = 1, nLineCount do
if lptrCurText == nil then
lptrCurText = ltabText[i]
else
lptrCurText = lptrCurText .. "\n" .. ltabText[i]
end
end
return lptrCurText
end
+