cocos 实现富文本

cocos 实现富文本

例子:

local str = string.format( "每次兑换扣除%s点活力,获得%s经验。", 
    string.format( "%s", 1),
    string.format( "%s", "FF7F00", "10000" )
)
-- 关键词 表示句子需要去解析。中可以跟color,size type fontPath等属性
--size 字体大小 color 字体颜色 type目前只实现了button:指这个字体可以被点击,如果一个文本中有多个font需要被点击并执行不同的代码,则加上id属性;fontPath 指字体路径。

RichTextCreator实现:

--[[
    富文本生成器
    例如:    dajljl
    解释成:生成《    dajljl》并拥有点击事件,并对调事件ID为1,字体颜色为#ffffff,字体大小为20
--]]

local RichTextCreator = class('RichTextCreator')

local fontPath = "fonts/font.ttf"
local DEFAULTSIZE =  20
local DEFAULTCOLOR = cc.c3b(0, 0, 0)
local DEFAULTWIDTH = 200

function RichTextCreator:TransformToRGBValue(value)
    local _r = tonumber("0x" .. string.sub(value, 1, 2))
    local _g = tonumber("0x" .. string.sub(value, 3, 4))
    local _b = tonumber("0x" .. string.sub(value, 5, 6))
    return cc.c3b(_r, _g, _b)
end

function RichTextCreator:createRichElement(richText, strValue, size, color)
    for _, value in pairs(strValue.strValues) do
        if value == "\n" then
            richText:pushBackElement(ccui.RichElementNewLine:create(0, color, 255))
        else
            local elementNode
            local fp = strValue.attributes.fontPath or fontPath
            if strValue.attributes.type == "button" then 
                local label = ccui.Text:create(value, fp, size)
                label:setTextColor(cc.c4b(color.r, color.g, color.b, 255))
                elementNode = ccui.RichElementCustomNode:create(0, cc.c3b(0, 0, 0), 255, label)

                label:setTouchEnabled(true)
                label:addClickEventListener( function()
                    if self.callback then
                        if nil == strValue.attributes.id then 
                            printError("strValue.attribute.buttonID = nil")
                        end
                        self.callback(strValue.attributes.id)
                    end
                end )
            else
                elementNode = ccui.RichElementText:create(0, color, 255, value, fp, size)
            end
            richText:pushBackElement(elementNode)
        end
    end

end

function RichTextCreator:createRichText(value, width, defaultSize, defaultColor, callback)
    width = width or DEFAULTWIDTH
    defaultSize = defaultSize or DEFAULTSIZE
    defaultColor = defaultColor or DEFAULTCOLOR

    if nil == value or string.len(value) == 0 then
        print("-------------------RichTextCreator:createRichText invalid value")
        return nil
    end

    self.callback = callback

    local _strValue = value
    _strValue = string.gsub(_strValue, "

", "") local _richText = ccui.RichText:create() _richText:ignoreContentAdaptWithSize(false) _richText:setContentSize(width, 0) local RichTextParser = require("utils.RichTextParser") local elements = RichTextParser:parser(_strValue) -- 遍历所有字块 for _, value in pairs(elements) do local color = value.attributes.color ~= nil and self:TransformToRGBValue(value.attributes.color) or defaultColor local size = value.attributes.size ~= nil and tonumber(value.attributes.size) or defaultSize self:createRichElement(_richText, value, size, color) end _richText:formatText() return _richText end function RichTextCreator:setCallBack( callback ) self.callback = callback end function RichTextCreator:setFontPath( path ) if cc.FileUtils:getInstance():isFileExist(path) == true then fontPath = path else printError(path.." is not Exist!!!!") end end return RichTextCreator

RichTextParser实现:

local RichTextParser = class("RichTextParser")

-- RichTextParser is good RichText
-- 
--

-- local results={
--     [1] = {
--         strValue = "",
--         attribute = {
--             size = 20,
--             url = "",
--             color = "",
--         },
--         strValues = {},
--     }
-- }

local function getNilElement( )
    local element= {
            strValue = "",
            attributes = {},
            strValues = {},
        }
    return element
end

--[[
    color='#ffffff' 字体颜色
    size='20' 字体大小
    type='button' 目前只支持点击事件(button)
    fontPath='font\font.ttf' 字体目录
    id='1' 在type=button的时候被使用并在回调中当作参数
--]]
local parserRule = {
    color = " color='#(.-)'",
    size = " size='(.-)'",
    type = " type='(.-)'",
    fontPath = " fontPath='(.-)'",
    id = " id='(.-)'",
}

function RichTextParser:parser(strValue)
    local elements = {}
    if nil == strValue or string.len(strValue) == 0 then 
        table.insert( elements, getNilElement() ) 
        return elements
    end
    local _strValue = strValue

    while string.len(_strValue) > 0 do
        local _startBeginFont, _startEndFont = string.find(_strValue, "", 1)

            for key, value in pairs(parserRule) do 
                local start, _, _colorValue = string.find(_strValue, value)
                if nil ~= start and start < _attributEnd then 
                    element.attributes[key] =  _colorValue
                end
            end

            local _endBeginFont, _endEndFont = string.find(_strValue, "", 1)
            element.strValue = string.sub(_strValue, _attributEnd + 1, _endBeginFont - 1)
            -- sub
            _strValue = string.sub(_strValue, _endEndFont + 1, -1)

        elseif nil == _startBeginFont then
            element.strValue = _strValue
            _strValue = ""
        else
            local strTemp = string.sub(_strValue, 1, _startBeginFont - 1)
            element.strValue = strTemp
            -- sub
            _strValue = string.sub(_strValue, _startBeginFont, -1)

        end
        table.insert( elements, element )
    end

    for _, element in pairs(elements) do
        local str = element.strValue
        local strs = {}
        while string.len(str) > 0 do
            local strTemp = "\n"
            if nil ~= string.find(str, "
", 1) then local _begin, _end = string.find(str, "
", 1) if _begin == 1 then str = string.sub(str, _end + 1, -1) else strTemp = string.sub(str, 1, _begin - 1) str = string.sub(str, _begin, -1) end else strTemp = str str = "" end table.insert( strs, strTemp ) end element.strValues = clone(strs) end return elements end return RichTextParser

cocos 实现富文本_第1张图片

你可能感兴趣的:(lua,cocos2D)