加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

cocos2dx CCLabelTTF 字体自动换行

发布时间:2020-12-14 21:25:10 所属栏目:百科 来源:网络整理
导读:我用的2.1.4版本的引擎,搞的我头疼死了。我也是在网上抄的一份,各种不行,然后自己修改他的,就可以了。 void initString() { //将中文进行转换为TTFstd::string_string = tipsInfo.tipsString; //初始化Tips字符串int index = 0;int index_max = strlen(_s
我用的2.1.4版本的引擎,搞的我头疼死了。我也是在网上抄的一份,各种不行,然后自己修改他的,就可以了。
void initString() { //将中文进行转换为TTF
			std::string	_string   = tipsInfo.tipsString; //初始化Tips字符串
			int index			  = 0;
			int index_max		  = strlen(_string.c_str());
			bool is_end			  = false;
			if (labelTTF_arr != nullptr)
			{
				labelTTF_arr->removeAllObjects();
			} else
			{
				labelTTF_arr		  = CCArray::create();
				labelTTF_arr->retain();
			}
			while (! is_end) { //格式转化
				//以上步骤是根据ASCII码找出中英文字符,并创建成一个CCLabelTTF对象存入labelTTF_arr数组中。
				if (_string[index] >= 0 && _string[index] <= 127) {
					string englishStr =_string.substr(index,1).c_str();
					labelTTF_arr->addObject(CCLabelTTF::create(englishStr.c_str(),fontMakertFilePath,12));
					index += 1;
				}
				else{
					string chineseStr = _string.substr(index,3).c_str();
					labelTTF_arr->addObject(CCLabelTTF::create(chineseStr.c_str(),12));
					index += 3;
				}
				if (index >= index_max) {
					is_end = true;
				}
			}
			initStringFormat(8,10,250); //设置对齐方式
}

void initStringFormat(float horizontalSpacing,float verticalSpacing,float lineWidth) {
		//下面创建的原理是在CCLabelTTF对象上添加子对象CCLabelTTF,以此组合成一句话,以左上角第一个字为锚点。。
	CCLabelTTF* pWillShowWords	= (CCLabelTTF*)labelTTF_arr->objectAtIndex(0);
	float nowWidth				= pWillShowWords->getContentSize().width;
	CCLabelTTF* pCurrentTTF		= pWillShowWords;
	CCLabelTTF* pBeginTTF		= pWillShowWords;

	int arr_count = labelTTF_arr->count();
	for (int i=1; i < arr_count; i++) {

		CCLabelTTF* updateTTF  = (CCLabelTTF*)labelTTF_arr->objectAtIndex(i);
		updateTTF->setAnchorPoint(ccp(0.0f,0.5f));
		const char *pLineBreak = ((CCLabelTTF *)labelTTF_arr->objectAtIndex(i))->getString();
		nowWidth += updateTTF->getContentSize().width;
		if (nowWidth >= lineWidth || (std::strcmp(pLineBreak,"n") == 0)) {

			nowWidth = pWillShowWords->getContentSize().width;
			
			if (std::strcmp(pLineBreak,"n") == 0)//在你的字符串里面添加一个n字符,其他字符也行(表示换行)
			{
				nowWidth = lineWidth; //换行
				continue;
			} 
			updateTTF->setPosition(ccp(0,-pCurrentTTF->getContentSize().height * 0.5 - verticalSpacing));
			pCurrentTTF  = pBeginTTF;
			pBeginTTF	 = updateTTF;
		}else{
			updateTTF->setPosition(ccp(pCurrentTTF->getContentSize().width + horizontalSpacing,pCurrentTTF->getContentSize().height * 0.5));
		}

		pCurrentTTF->addChild(updateTTF);
		pCurrentTTF = updateTTF;
	}
	
	this->addChild(pWillShowWords,100); //test
	//TODO/
	//设置你字体坐标:pWillShowWords->setPosition(..)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读