执行后效果:

cocos2d-x之 利用富文本控件解析xhml标签(文字标签,图片标签,换行标签,标签属性)-LMLPHP

前端使用:

cocos2d-x之 利用富文本控件解析xhml标签(文字标签,图片标签,换行标签,标签属性)-LMLPHP

后台SuperRichText解析code

void SuperRichText::renderNode(tinyxml2::XMLNode *node){

while (node!=nullptr) {

if (node->ToText()) {

CCLOG("文本信息:%s",node->ToText()->Value());

auto n=node->ToText();

std::u16string text;

StringUtils::UTF8ToUTF16(n->Value(),text);

std::u16string::size_type pos=0;

pos=text.find('\n');

while ((pos!=std::u16string::npos)) {

text.erase(pos,1);

pos=text.find('\n',pos);

}

pos=0;

pos=text.find('\r');

while ((pos!=std::u16string::npos)) {

text.erase(pos,1);

pos=text.find('\r',pos);

}

std::string utf8Text;

StringUtils::UTF16ToUTF8(text,utf8Text);

auto font=_fontList[_fontList.size()-1];

auto textElement=ui::RichElementText::create(0,font.color,font.opacity,utf8Text,font.fontName,font.fontSize);

_line->pushBackElement(textElement);

}else if (node->ToElement()){

auto n=node->ToElement();

std::string name=n->Name();

std::transform(name.begin(),name.end(),name.begin(),::toupper);

if (name=="FONT") {

CCLOG("字体标签");

auto attr=n->FirstAttribute();

FontInfo newFont=_fontList[_fontList.size()-1];

while (attr!=nullptr) {

//遍历所有属性

std::string attrName=attr->Name();

std::transform(attrName.begin(),attrName.end(),attrName.begin(),::toupper);

if (attrName=="FACE") {

//设置字体

newFont.fontName=attr->Value();

}else if (attrName=="COLOR"){

//设置颜色

newFont.color=charToColor3B(attr->Value());

}else if(attrName=="SIZE"){

//设置大小

newFont.fontSize=attr->IntValue();

}else if (attrName=="OPACITY"){

//设置不透明度

newFont.opacity=attr->IntValue();

}

attr=attr->Next();

}

_fontList.push_back(newFont);//添加新字体

renderNode(n->FirstChild());//继续渲染子集

_fontList.pop_back();//移除新字体

}else if (name=="IMG") {

CCLOG("图片标签");

//图片标签的属性

auto attr=n->FirstAttribute();

const char *src;

Color3B col(255,255,255);

GLubyte opacity=255;

while (attr!=nullptr) {

//遍历所有属性

std::string attrName=attr->Name();

std::transform(attrName.begin(),attrName.end(),attrName.begin(),::toupper);

if (attrName=="SRC") {

//设置图片路径

src=attr->Value();

}else if (attrName=="COLOR"){

//设置颜色

col=charToColor3B(attr->Value());

}else if (attrName=="OPACITY"){

//设置不透明度

opacity=attr->IntValue();

}

attr=attr->Next();

}

auto img=ui::RichElementImage::create(0,col,opacity,src);

_line->pushBackElement(img);

}else if (name=="BR") {

CCLOG("换行标签");

addNewLine();

}

}

node=node->NextSibling();

}

}

04-14 16:22