Nanfeng

Notes on software development, code, and curious ideas

Drawing an Underline Beneath Text in Cocos2d-x Lua

An underline is simply a short line positioned below the text. The following helper creates a DrawNode containing a segment between two points:

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
-- Creates and returns a line DrawNode.
-- @param points {{x1, y1}, {x2, y2}}
-- @param params Optional borderColor, borderWidth, and scale

function display.newLine(points, params)
local radius
local borderColor
local scale

if not params then
borderColor = cc.c4f(0, 0, 0, 1)
radius = 0.5
scale = 1.0
else
borderColor = params.borderColor or cc.c4f(0, 0, 0, 1)
radius = (params.borderWidth and params.borderWidth / 2) or 0.5
scale = checknumber(params.scale or 1.0)
end

local scaledPoints = {}
for i, point in ipairs(points) do
scaledPoints[i] = cc.p(point[1] * scale, point[2] * scale)
end

local drawNode = cc.DrawNode:create()
drawNode:drawSegment(
scaledPoints[1],
scaledPoints[2],
radius,
borderColor
)
return drawNode
end

Example:

1
2
3
4
5
6
7
8
local underline = display.newLine(
{{10, 10}, {100, 10}},
{
borderColor = cc.c4f(1, 0, 0, 1),
borderWidth = 1
}
)
label:addChild(underline)

Adjust the endpoints to the label width and position the line relative to the label’s anchor point.

+