--[[
@desc: 创建以特殊字符隔开并修改文本颜色的富文本
--@str:完整字符串
--@fontSize:字体大小
--@tbColor: {[1] = 普通字体颜色, [2] = 标记字体颜色}
--@iMaxWidth: label最大长度
@return: node,iHeight
]]
function Tool:CreateColorText(str, iFontSize, tbColor, iMaxWidth)
local pNode = cc.Node:create()
local allStr = {}
local r = {}
if (str == nil) then
return nil
end
for word in string.gmatch(str, "%P+[%s|%p]") do
if string.find(word, " ") then
for sub in string.gmatch(word, "%S+%s*") do
table.insert(allStr, sub)
end
else
table.insert(allStr, word)
end
end
local tbHight = {}
string.gsub(str, "「.-」", function(w) --匹配字符串
table.insert(tbHight, w)
end)
local iLineRows = iFontSize * 1.2
local iHeight = 0
local start = string.gsub(str, 1, 1)
local strCurLine = ""
local tbShow = {}
local iLineWidth = 0
local strTmpLine = ""
for i=1,#allStr do
local showcolor = tbColor[1]
local bLight = false
for j=1,#tbHight do
if string.find(allStr[i], tbHight[j]) then
allStr[i] = string.gsub(allStr[i], "[「|」]", "")
bLight = true
break
end
end
local pTmpLabel = cc.Label:createWithSystemFont(strTmpLine..allStr[i], SYSTEM_FONT_ARIAL, iFontSize)
local iWillLineWidth = pTmpLabel:getContentSize().width
if bLight or iWillLineWidth > iMaxWidth or i == #allStr then
if i == #allStr then
strCurLine = strCurLine..allStr[i]
end
local pLabShow = cc.Label:createWithSystemFont(strCurLine, SYSTEM_FONT_ARIAL, iFontSize)
pLabShow:setColor(showcolor)
pLabShow:setPosition(cc.p(iLineWidth, iHeight))
pNode:addChild(pLabShow)
pLabShow:setAnchorPoint(cc.p(0, 0.5))
if iWillLineWidth > iMaxWidth then
strTmpLine = allStr[i]
iHeight = iHeight - iLineRows
strCurLine = allStr[i]
iLineWidth = 0
else
strTmpLine = strTmpLine..allStr[i]
iLineWidth = iWillLineWidth
end
else
strTmpLine = strTmpLine..allStr[i]
end
if bLight then
showcolor = tbColor[2]
strCurLine = allStr[i]
local pLabShow = cc.Label:createWithSystemFont(strCurLine, SYSTEM_FONT_ARIAL, iFontSize)
pLabShow:setColor(showcolor)
if iWillLineWidth > iMaxWidth then
pLabShow:setPosition(cc.p(iLineWidth, iHeight))
iLineWidth = pLabShow:getContentSize().width
else
pLabShow:setPosition(cc.p(iLineWidth - pLabShow:getContentSize().width, iHeight))
end
pNode:addChild(pLabShow)
pLabShow:setAnchorPoint(cc.p(0, 0.5))
strCurLine = ""
elseif iWillLineWidth <= iMaxWidth then
strCurLine = strCurLine..allStr[i]
end
end
return pNode, -iHeight
end
lua按照标点符号或空格分割单词
于 2022-11-29 20:01:50 首次发布