说一说cocos2dx 获得字符宽度的问题,下面放出源代码,供大家参考和学习。因为项目需要,所以我就弄了一下,现在给大家放出来,大家可以参考学习和交流,哪有问题可以指正。根据输入字符串,计算字符串所需要占的Size。封装代码如下,只需传入字符串,即可返回Size:
- Size ChartDemoScene::calculateFontSize(const char *str )
- {
- std::string tempString = str;
- log("tempString = %s",tempString.c_str());
- size_t computeCount = tempString.size(); //如果字符串很长每次抽取100个字符来计算size;
- Size size = Size(0,0);
- for (int i = 0; i<computecount ;)="" {="" std::string="" substring="tempString.substr(i,1);" if="" ((substring.c_str()[0]="" &="" 0x80="" )!="0)" 是汉字="" ,="" 3);="" i="" +="3;" }="" else="" i++;="" cclog("substring="%s" ",substring.c_str());="" auto="" templabel="LabelTTF::create(substring.c_str(),"",25);" templabel-="">setHorizontalAlignment(cocos2d::TextHAlignment::LEFT);
- Size tmpLsize = tempLabel->getContentSize();
- size.width+=tmpLsize.width;
- }
- float fHeight= 0;
- if( size.width > chartWidth)//大于容器的宽度
- {
- fHeight = (size.width / 200 );//计算需要多少行
- }
- int nHeight = ceil(fHeight);
- if (nHeight == 0)
- {
- nHeight = 1;
- }
- Size labelSize ;
- if (size.width < chartWidth)
- {
- labelSize = Size(size.width,nHeight*32);//计算容器的Size
- }
- else
- {
- labelSize = Size(chartWidth,nHeight*28);
- }
- //CCLog("labelSize = (%f, %f)",labelSize.width ,labelSize.height);
- //CCLog("fHeight = %f nHeight = %d " ,fHeight ,nHeight);
- return labelSize;
- }</computecount>