Nanfeng

Notes on software development, code, and curious ideas

Wrapping Label Text in Cocos2d-x Lua

Environment: Cocos2d-x 3.17
Language: Lua

For a cc.Label, the simplest wrapping method is usually to assign a width and use an overflow or dimensions mode supported by the engine version:

1
2
3
4
5
6
7
8
local label = cc.Label:createWithSystemFont(
longText,
"Arial",
24,
cc.size(360, 0),
cc.TEXT_ALIGNMENT_LEFT,
cc.VERTICAL_TEXT_ALIGNMENT_TOP
)

For a UI text widget:

1
2
3
textWidget:ignoreContentAdaptWithSize(false)
textWidget:setContentSize(cc.size(360, 160))
textWidget:setTextHorizontalAlignment(cc.TEXT_ALIGNMENT_LEFT)

This lets the engine wrap according to font metrics, which is more accurate than treating Chinese characters as three bytes and ASCII characters as one byte.

If the project requires manual wrapping, iterate UTF-8 code points and measure candidate lines with the actual font. Insert \n at word boundaries where possible. Byte-based splitting can break multibyte characters and cannot reliably predict rendered width for proportional fonts, emoji, combining marks, or mixed scripts.

+