찾다
웹 프론트엔드HTML 튜토리얼[寒江孤叶丶的Cocos2d-x之旅_33]RichTextEx一款通过HTML标签控制文字样式的富文本控件_html/css_WEB-ITnose

RichTextEx一款通过HTML标签控制文字样式的富文本控件

博客地址:

下载地址

Github链接

这个是干什么的

将如下文字内容
"【世】寒江孤叶:HelloWorld"
生成如图所示样式的RichText(支持图片以及闪烁、旋转和其他自定义的效果、控件)

关于它

这个是LUA版本的,CPP版本的没写,欢迎移植CPP和JS版本
LUA文件是用一个别人写的文件修改的(添加一些功能,修复几个BUG……话说之前跑都跑不起来啊亲……什么鬼)
另外抱歉,找不到他的Github链接了……
· TTF字体支持描边,系统字体是不支持的

使用说明

RichTextEx使用起来非常简单,只要将RichTextEx.lua复制到你的项目目录中,并require它就可以了
比如这样:

APUtils = APUtils or {}  APUtils.RichTextEx = APUtils.RichTextEx or require("APUtils/gui/RichTextEx.lua")

使用RichText来创建一个富文本是非常简单的:

local txt = RichTextEx:create() -- 或 RichTextEx:create(26, cc.c3b(10, 10, 10))txt:setText("<outline><underline true><font res>您的元宝和银券不足请充值,或领取抽取元宝奖励!")-- 多行模式要同时设置 ignoreContentAdaptWithSize(false) 和 contentSizetxt:setMultiLineMode(true)  -- 这行其实就是 ignoreContentAdaptWithSize(false)txt:setContentSize(200, 400)someNode:addChild(txt)</font></underline></outline>

如果字符串是由用户输入的话,建议调用RichTextEx.htmlEncode("")将用户输入内容编码一下,以避免用户输入关键字符导致无法预知的错误
在生成字符串之前会自动调用RichTextEx.htmlDecode,如果你自定义了用于显示文字内容的控件,请记得调用它,以对字符串进行解码

RichTextEx的基本选项

 =   = 文字颜色                = 字体大小<font arial>        = 文字字体 支持TTF<img  filename alt="[寒江孤叶丶的Cocos2d-x之旅_33]RichTextEx一款通过HTML标签控制文字样式的富文本控件_html/css_WEB-ITnose" >      = 图片(filename 可以是已经在 SpriteFrameCache 里的 key,或磁盘文件)<img _32 fname alt="[寒江孤叶丶的Cocos2d-x之旅_33]RichTextEx一款通过HTML标签控制文字样式的富文本控件_html/css_WEB-ITnose" >   = 指定大小的图片   2> = 当前字体大小 +-*/                 = 颜色、字体和字体大小恢复默认\n \t               = 换行 和 tab,可能暂时实现得不是很好 最好不要用 如果需要换行你可以创建多个RichText然后依次放好<outline>         = 设置1像素描边,只支持TTF字体<underline true>    = 是否开启下划线</underline></outline></img_32></font>

RichTextEx的示例选项 (在 RichTextEx.defaultCb 中提供)

<blink>      = (动画)闪烁那些文字<rotate>     = (动画)旋转那些文字<scale>      = (动画)缩放那些文字(但如果你做了 setText(t, callback) 除非你在 callback 主动调用 defaultCb,否则以上选项会被忽略)   </scale></rotate></blink>

你可以对功能进行扩展

`<img _w http: alt="[寒江孤叶丶的Cocos2d-x之旅_33]RichTextEx一款通过HTML标签控制文字样式的富文本控件_html/css_WEB-ITnose" > 例如从网络下载图片`</img_w>

同时支持自定义特殊语法,加入 callback 回调就可,如

txt:setText("XXXXX <aaaa haha> <bbbb> <cccc> xxx", function(text, sender) -- 第二个参数 sender 可选    -- 对每一个自定义的  都会调用此 callback    -- text 就等于 *** (不含)    -- 简单的返回一个 Node 的子实例就可,如    -- 如果接收第二个参数 sender,就可获取当前文字大小、颜色: sender._fontSize、sender._textColor    if string.sub(text, 1, 4) == "aaaa" then        return ccui.Text:create("aaa111" .. string.sub(text, 6)), "", 32)        --这里如果为了代码的健壮性最好加入self:htmlDecode        --return ccui.Text:create(self:htmlDecode("aaa111" .. string.sub(text, 6))), "", 32)    elseif text == "bbbb" then        -- 用当前文字大小和颜色        local lbl = ccui.Text:create("bbb111", "", sender._fontSize)        lbl:setTextColor(sender._textColor)        return lbl    elseif string.sub(text, 1, 4) == "CCCC" then        local img = ccui.ImageView:create(....)        img:setScale(...)        img:runAction(...)        return img    endend)</cccc></bbbb></aaaa>

你还要做什么

为了支持描边和下划线还要修改一下Cocos的源码
UIRichText.h和UIRichText.cpp放到项目源码目录 替换原来的
路径:frameworks/cocos2d-x/cocos/ui
(修改内容主要三个方面:加入下划线设置,加入描边设置,RichText可以自动更改高度了)
另外还需要修改toLua文件
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp
18878行左右能看到两个函数
int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S)

int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S)
将这两个函数的实现替换为如下形式:

int lua_cocos2dx_ui_RichElementText_init(lua_State* tolua_S){    int argc = 0;    cocos2d::ui::RichElementText* cobj = nullptr;    bool ok  = true;#if COCOS2D_DEBUG >= 1    tolua_Error tolua_err;#endif#if COCOS2D_DEBUG >= 1    if (!tolua_isusertype(tolua_S,1,"ccui.RichElementText",0,&tolua_err)) goto tolua_lerror;#endif    cobj = (cocos2d::ui::RichElementText*)tolua_tousertype(tolua_S,1,0);#if COCOS2D_DEBUG >= 1    if (!cobj)     {        tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_ui_RichElementText_init'", nullptr);        return 0;    }#endif    argc = lua_gettop(tolua_S)-1;    if (argc == 8)    {        int arg0;        cocos2d::Color3B arg1;        uint16_t arg2;        std::string arg3;        std::string arg4;        double arg5;        int arg6;        bool arg7;        ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:init");        ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:init");        ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:init");        ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:init");        ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:init");        ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:init");        ok &= luaval_to_int32(tolua_S, 8,&arg6, "ccui.RichElementText:init");        ok &= luaval_to_boolean(tolua_S, 9,&arg7, "ccui.RichElementText:init");        if(!ok)        {            tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementText_init'", nullptr);            return 0;        }        bool ret = cobj->init(arg0, arg1, arg2, arg3, arg4, arg5,arg6,arg7);        tolua_pushboolean(tolua_S,(bool)ret);        return 1;    }    luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.RichElementText:init",argc, 6);    return 0;#if COCOS2D_DEBUG >= 1    tolua_lerror:    tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_ui_RichElementText_init'.",&tolua_err);#endif    return 0;}int lua_cocos2dx_ui_RichElementText_create(lua_State* tolua_S){    int argc = 0;    bool ok  = true;#if COCOS2D_DEBUG >= 1    tolua_Error tolua_err;#endif#if COCOS2D_DEBUG >= 1    if (!tolua_isusertable(tolua_S,1,"ccui.RichElementText",0,&tolua_err)) goto tolua_lerror;#endif    argc = lua_gettop(tolua_S) - 1;    if (argc == 6)    {        int arg0;        cocos2d::Color3B arg1;        uint16_t arg2;        std::string arg3;        std::string arg4;        double arg5;        ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create");        ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create");        ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create");        ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create");        ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create");        ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create");        if(!ok)        {            tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementText_create'", nullptr);            return 0;        }        cocos2d::ui::RichElementText* ret = cocos2d::ui::RichElementText::create(arg0, arg1, arg2, arg3, arg4, arg5);        object_to_luaval<:ui::richelementtext>(tolua_S, "ccui.RichElementText",(cocos2d::ui::RichElementText*)ret);        return 1;    }    if (argc == 7)    {        int arg0;        cocos2d::Color3B arg1;        uint16_t arg2;        std::string arg3;        std::string arg4;        double arg5;        int arg6;        ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create");        ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create");        ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create");        ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create");        ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create");        ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create");        ok &= luaval_to_int32(tolua_S, 8,&arg6, "ccui.RichElementText:create");        if(!ok)        {            tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementText_create'", nullptr);            return 0;        }        cocos2d::ui::RichElementText* ret = cocos2d::ui::RichElementText::create(arg0, arg1, arg2, arg3, arg4, arg5, arg6);        object_to_luaval<:ui::richelementtext>(tolua_S, "ccui.RichElementText",(cocos2d::ui::RichElementText*)ret);        return 1;    }    if (argc == 8)    {        int arg0;        cocos2d::Color3B arg1;        uint16_t arg2;        std::string arg3;        std::string arg4;        double arg5;        int arg6;        bool arg7;        ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccui.RichElementText:create");        ok &= luaval_to_color3b(tolua_S, 3, &arg1, "ccui.RichElementText:create");        ok &= luaval_to_uint16(tolua_S, 4,&arg2, "ccui.RichElementText:create");        ok &= luaval_to_std_string(tolua_S, 5,&arg3, "ccui.RichElementText:create");        ok &= luaval_to_std_string(tolua_S, 6,&arg4, "ccui.RichElementText:create");        ok &= luaval_to_number(tolua_S, 7,&arg5, "ccui.RichElementText:create");        ok &= luaval_to_int32(tolua_S, 8,&arg6, "ccui.RichElementText:create");        ok &= luaval_to_boolean(tolua_S, 9,&arg7, "ccui.RichElementText:create");        if(!ok)        {            tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_RichElementText_create'", nullptr);            return 0;        }        cocos2d::ui::RichElementText* ret = cocos2d::ui::RichElementText::create(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);        object_to_luaval<:ui::richelementtext>(tolua_S, "ccui.RichElementText",(cocos2d::ui::RichElementText*)ret);        return 1;    }    luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "ccui.RichElementText:create",argc, 6);    return 0;#if COCOS2D_DEBUG >= 1    tolua_lerror:    tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_ui_RichElementText_create'.",&tolua_err);#endif    return 0;}  </:ui::richelementtext></:ui::richelementtext></:ui::richelementtext>

重新编译一下项目,然后就可以在项目里用了

下个版本要更新的内容

1.继续修改Cocos2d-x的RichText的源码,使其更好的支持tab和换行
2.加入可点击的文字,以及点击后变色
3.为系统字体加入描边(判断为系统字体时,描边采用阴影替代)

其他

下划线实现的非常拙略,如果你有更好的方法一定要告诉我。
也许您希望得到一个不需要修改Cocos2d-x源代码的版本(此版本支持描边和下划线)
欢迎交流QQ:446569365

版权声明:本文为博主原创文章,未经博主允许不得转载。

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
공식 계정 웹 페이지의 캐싱 업데이트에 어려움 : 버전 업데이트 후 사용자 경험에 영향을 미치는 이전 캐시를 피하는 방법은 무엇입니까?공식 계정 웹 페이지의 캐싱 업데이트에 어려움 : 버전 업데이트 후 사용자 경험에 영향을 미치는 이전 캐시를 피하는 방법은 무엇입니까?Mar 04, 2025 pm 12:32 PM

공식 계정 웹 페이지 업데이트 캐시, 이것은 간단하고 간단하며 냄비를 마시기에 충분히 복잡합니다. 공식 계정 기사를 업데이트하기 위해 열심히 노력했지만 사용자는 여전히 기존 버전을 열었습니까? 이 기사에서는이 뒤에있는 비틀기와 회전을 살펴 보고이 문제를 우아하게 해결하는 방법을 살펴 보겠습니다. 읽은 후에는 다양한 캐싱 문제를 쉽게 처리 할 수있어 사용자가 항상 가장 신선한 콘텐츠를 경험할 수 있습니다. 기본 사항에 대해 먼저 이야기 해 봅시다. 액세스 속도를 향상시키기 위해 브라우저 또는 서버는 일부 정적 리소스 (예 : 그림, CSS, JS) 또는 페이지 컨텐츠를 저장합니다. 다음에 액세스 할 때 다시 다운로드하지 않고도 캐시에서 직접 검색 할 수 있으며 자연스럽게 빠릅니다. 그러나 이것은 또한 양날의 검입니다. 새 버전은 온라인입니다.

HTML5 양식 유효성 검사 속성을 사용하여 사용자 입력을 유효성있게하려면 어떻게합니까?HTML5 양식 유효성 검사 속성을 사용하여 사용자 입력을 유효성있게하려면 어떻게합니까?Mar 17, 2025 pm 12:27 PM

이 기사에서는 브라우저에서 직접 사용자 입력을 검증하기 위해 필요한, Pattern, Min, Max 및 Length 한계와 같은 HTML5 양식 검증 속성을 사용하는 것에 대해 설명합니다.

HTML5의 크로스 브라우저 호환성에 대한 모범 사례는 무엇입니까?HTML5의 크로스 브라우저 호환성에 대한 모범 사례는 무엇입니까?Mar 17, 2025 pm 12:20 PM

기사는 HTML5 크로스 브라우저 호환성을 보장하기위한 모범 사례에 대해 논의하고 기능 감지, 점진적 향상 및 테스트 방법에 중점을 둡니다.

웹 페이지의 PNG 이미지에 뇌졸중 효과를 효율적으로 추가하는 방법은 무엇입니까?웹 페이지의 PNG 이미지에 뇌졸중 효과를 효율적으로 추가하는 방법은 무엇입니까?Mar 04, 2025 pm 02:39 PM

이 기사는 CSS를 사용한 웹 페이지에 효율적인 PNG 테두리 추가를 보여줍니다. CSS는 JavaScript 또는 라이브러리에 비해 우수한 성능을 제공하며, 미묘하거나 눈에 띄는 효과를 위해 테두리 너비, 스타일 및 색상 조정 방법을 자세히 설명합니다.

& lt; datalist & gt의 목적은 무엇입니까? 요소?& lt; datalist & gt의 목적은 무엇입니까? 요소?Mar 21, 2025 pm 12:33 PM

이 기사는 HTML & LT; Datalist & GT에 대해 논의합니다. 자동 완성 제안을 제공하고, 사용자 경험을 향상시키고, 오류를 줄임으로써 양식을 향상시키는 요소. 문자 수 : 159

& lt; Progress & Gt의 목적은 무엇입니까? 요소?& lt; Progress & Gt의 목적은 무엇입니까? 요소?Mar 21, 2025 pm 12:34 PM

이 기사는 HTML & lt; Progress & Gt에 대해 설명합니다. 요소, 그 목적, 스타일 및 & lt; meter & gt의 차이; 요소. 주요 초점은 & lt; progress & gt; 작업 완료 및 & lt; meter & gt; Stati의 경우

html5 & lt; time & gt; 의미 적으로 날짜와 시간을 나타내는 요소?html5 & lt; time & gt; 의미 적으로 날짜와 시간을 나타내는 요소?Mar 12, 2025 pm 04:05 PM

이 기사는 html5 & lt; time & gt; 시맨틱 날짜/시간 표현 요소. 인간이 읽을 수있는 텍스트와 함께 기계 가독성 (ISO 8601 형식)에 대한 DateTime 속성의 중요성을 강조하여 Accessibilit를 향상시킵니다.

& lt; meter & gt의 목적은 무엇입니까? 요소?& lt; meter & gt의 목적은 무엇입니까? 요소?Mar 21, 2025 pm 12:35 PM

이 기사는 HTML & lt; meter & gt에 대해 설명합니다. 범위 내에 스칼라 또는 분수 값을 표시하는 데 사용되는 요소 및 웹 개발의 일반적인 응용 프로그램. & lt; meter & gt; & lt; Progress & Gt; 그리고 Ex

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!