Cocos2d-x计算字符串Size方法

前端之家收集整理的这篇文章主要介绍了Cocos2d-x计算字符串Size方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

项目需要,根据输入字符串,计算字符串所需要占的Size。封装代码如下,只需传入字符串,即可返回Size:

  1. Size ChartDemoScene::calculateFontSize(const char *str )
  2. {
  3. std::string tempString = str;
  4. log("tempString = %s",tempString.c_str());
  5. size_t computeCount = tempString.size(); //如果字符串很长每次抽取100个字符来计算size;
  6. Size size = Size(0,0);
  7. for (int i = 0; i<computeCount ;)
  8. {
  9. std::string substring = tempString.substr(i,1);
  10. if ((substring.c_str()[0] & 0x80 )!=0) //是汉字
  11. {
  12. substring = tempString.substr(i,3);
  13. i += 3;
  14. }
  15. else
  16. {
  17. i++;
  18. }
  19. //CCLog("subString = %s ",substring.c_str());
  20. auto tempLabel = LabelTTF::create(substring.c_str(),"",25);
  21. tempLabel->setHorizontalAlignment(cocos2d::TextHAlignment::LEFT);
  22. Size tmpLsize = tempLabel->getContentSize();
  23. size.width+=tmpLsize.width;
  24. }
  25. float fHeight= 0;
  26. if( size.width > chartWidth)//大于容器的宽度
  27. {
  28. fHeight = (size.width / 200 );//计算需要多少行
  29. }
  30. int nHeight = ceil(fHeight);
  31. if (nHeight == 0)
  32. {
  33. nHeight = 1;
  34. }
  35. Size labelSize ;
  36. if (size.width < chartWidth)
  37. {
  38. labelSize = Size(size.width,nHeight*32);//计算容器的Size
  39. }
  40. else
  41. {
  42. labelSize = Size(chartWidth,nHeight*28);
  43. }
  44. //CCLog("labelSize = (%f,%f)",labelSize.width,labelSize.height);
  45. //CCLog("fHeight = %f nHeight = %d ",fHeight,nHeight);
  46. return labelSize;
  47. }

例子:

1、AppDelegate.cpp中添加如下代码

  1. auto scene = ChartDemoScene::createScene();
  2.  
  3. // run
  4. director->runWithScene(scene);
(1)ChartDemoScene.hChartDemoScene.h
  1. //
  2. // ChartDemoScene.h
  3. // chartDemo
  4. //
  5. // Created by chen on 14-9-2.
  6. //
  7. //
  8.  
  9. #ifndef __chartDemo__ChartDemoScene__
  10. #define __chartDemo__ChartDemoScene__
  11.  
  12. #include "cocos2d.h"
  13. #include "ui/CocosGUI.h"
  14. #include "../cocos2d/extensions/cocos-ext.h"
  15. using namespace cocos2d::ui;
  16. USING_NS_CC;
  17. USING_NS_CC_EXT;
  18.  
  19. class ChartDemoScene : public cocos2d::Layer//,public cocos2d::extension::EditBoxDelegate
  20. {
  21. public:
  22. // there's no 'id' in cpp,so we recommend returning the class instance pointer
  23. static cocos2d::Scene* createScene();
  24. // Here's a difference. Method 'init' in cocos2d-x returns bool,instead of returning 'id' in cocos2d-iphone
  25. virtual bool init();
  26. // a selector callback
  27. void menuCloseCallback(cocos2d::Ref* pSender);
  28. // implement the "static create()" method manually
  29. CREATE_FUNC(ChartDemoScene);
  30. // virtual void editBoxEditingDidBegin(cocos2d::extension::EditBox* editBox);
  31. // virtual void editBoxEditingDidEnd(cocos2d::extension::EditBox* editBox);
  32. // virtual void editBoxTextChanged(cocos2d::extension::EditBox* editBox,const std::string& text);
  33. // virtual void editBoxReturn(cocos2d::extension::EditBox* editBox);
  34.  
  35. void touchEvent(Ref *pSender,Widget::TouchEventType type);
  36. void textFieldEvent(Ref* pSender,TextField::EventType type);
  37. void showAlertShow(std::string contentString);
  38. void alertCallback(ui::Text* alert);
  39. Size calculateFontSize(const char *str);
  40. std::string getcurrTime();//获取当前年月日
  41. std::string getcurrMonthTime();//获取时分秒
  42.  
  43. // EditBox* editText;
  44. TextField* editText;
  45. Text* text;
  46. TextField* _text;//获取删除Item的内容
  47. std::string file_path;//存放消息记录
  48. TextField* textContent;
  49. ui::Button* sendBtn;
  50. std::string str;
  51. Size winSize;
  52. float chartWidth;
  53. size_t length;
  54. ui::ListView* _listView;
  55. };
  56. #endif /* defined(__chartDemo__ChartDemoScene__) */

(2)ChartDemoScene.cpp

  1. #include "ChartDemoScene.h"
  2. #include "stdio.h"
  3.  
  4. enum alertTag
  5. {
  6. Alert_Tag = 1000
  7. }AlertTag;
  8.  
  9. enum textTag
  10. {
  11. T_Tag = 100
  12. }TextTag;
  13.  
  14. USING_NS_CC;
  15. int count = 1;
  16. int _rem = 0;
  17. Scene* ChartDemoScene::createScene()
  18. {
  19. // 'scene' is an autorelease object
  20. auto scene = Scene::create();
  21. scene->setColor(Color3B::BLACK);
  22. // 'layer' is an autorelease object
  23. auto layer = ChartDemoScene::create();
  24. layer->setAnchorPoint(Vec2::ANCHOR_MIDDLE_BOTTOM);
  25. layer->setContentSize(Size(640,960));
  26. // add layer as a child to scene
  27. scene->addChild(layer);
  28. // return the scene
  29. return scene;
  30. }
  31.  
  32. // on "init" you need to initialize your instance
  33. bool ChartDemoScene::init()
  34. {
  35. bool bRet = false;
  36. do{
  37. CC_BREAK_IF(!Layer::init());
  38. //大背景
  39. winSize = Director::getInstance()->getWinSize();
  40. file_path = FileUtils::getInstance()->getWritablePath() + "chartContent.txt";
  41. chartWidth = winSize.width *3 / 5;
  42. auto sprite = Sprite::create("orange_edit.png");
  43. sprite->setScaleX(winSize.width / sprite->getContentSize().width);
  44. sprite->setScaleY(winSize.height / sprite->getContentSize().height);
  45. sprite->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
  46. sprite->setPosition(Vec2(winSize.width/2,winSize.height/2));
  47. addChild(sprite);
  48. auto layerColor = LayerColor::create(Color4B(43,177,233,255));
  49. layerColor->setContentSize(Size(winSize.width,100));
  50. layerColor->ignoreAnchorPointForPosition(false);
  51. layerColor->setAnchorPoint(Vec2::ANCHOR_MIDDLE_TOP);
  52. layerColor->setPosition(Vec2(winSize.width/2,winSize.height));
  53. addChild(layerColor,4);
  54. //底部输入栏
  55. auto layout = Layout::create();
  56. layout->setSize(Size(winSize.width,100));
  57. layout->setAnchorPoint(Vec2::ZERO);
  58. layout->setPosition(Vec2::ZERO);
  59. layout->setBackGroundColorType(cocos2d::ui::Layout::BackGroundColorType::SOLID);
  60. layout->setBackGroundColor(Color3B(185,185,185));
  61. //消息显示
  62. _listView = ListView::create();
  63. _listView->setDirection(ui::ScrollView::Direction::VERTICAL);
  64. _listView->setTouchEnabled(true);
  65. _listView->setBounceEnabled(true);
  66. _listView->setGravity(cocos2d::ui::ListView::Gravity::BOTTOM);
  67. // _listView->setItemsMargin(2);
  68. _listView->setBackGroundColorType(cocos2d::ui::Layout::BackGroundColorType::SOLID);
  69. _listView->setBackGroundColor(Color3B::WHITE);
  70. _listView->setSize(Size(winSize.width,winSize.height-layout->getSize().height-25-100));
  71. _listView->setAnchorPoint(Vec2::ANCHOR_MIDDLE_BOTTOM);
  72. _listView->setPosition(Vec2(winSize.width/2,layout->getSize().height+25));
  73. addChild(_listView);
  74. //底部输入框背景
  75. auto bg = Sprite::create("whitebg.png");
  76. bg->setScaleX(winSize.width*3/5 / bg->getContentSize().width);
  77. bg->setScaleY(80 / bg->getContentSize().height);
  78. bg->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
  79. bg->setPosition(Vec2(winSize.width/5,layout->getSize().height/2));
  80. layout->addChild(bg);
  81. //
  82. editText = TextField::create("",30);
  83. editText->ignoreContentAdaptWithSize(false);
  84. editText->setSize(Size(winSize.width*3/5,80));
  85. editText->setTextHorizontalAlignment(cocos2d::TextHAlignment::LEFT);
  86. editText->setTextVerticalAlignment(cocos2d::TextVAlignment::BOTTOM);
  87. editText->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
  88. editText->setPosition(Vec2(winSize.width/5,layout->getSize().height/2));
  89. editText->setColor(Color3B::BLACK);
  90. editText->addEventListener(CC_CALLBACK_2(ChartDemoScene::textFieldEvent,this));
  91. layout->addChild(editText);
  92. addChild(layout);
  93. //发送按钮
  94. sendBtn = ui::Button::create("orange_edit.png");
  95. sendBtn->setAnchorPoint(Vec2::ANCHOR_MIDDLE_RIGHT);
  96. sendBtn->setPosition(Vec2(winSize.width - 20,layout->getSize().height/2));
  97. addChild(sendBtn);
  98. sendBtn->addTouchEventListener(CC_CALLBACK_2(ChartDemoScene::touchEvent,this));
  99. auto alert_Text = ui::Text::create();
  100. alert_Text->setSize(Size(50,200));
  101. alert_Text->setTag(Alert_Tag);
  102. alert_Text->setOpacity(0);
  103. alert_Text->setFontSize(35);
  104. char* userdata = "11";
  105. alert_Text->setUserData(userdata);
  106. alert_Text->setColor(Color3B::BLACK);
  107. alert_Text->setPosition(Vec2(winSize.width/2,winSize.height/8));
  108. addChild(alert_Text);
  109.  
  110. bRet = true;
  111. }while(0);
  112. return bRet;
  113. }
  114.  
  115. Size ChartDemoScene::calculateFontSize(const char *str )
  116. {
  117. std::string tempString = str;
  118. log("tempString = %s",25);
  119. tempLabel->setHorizontalAlignment(cocos2d::TextHAlignment::LEFT);
  120. Size tmpLsize = tempLabel->getContentSize();
  121. size.width+=tmpLsize.width;
  122. }
  123. float fHeight= 0;
  124. if( size.width > chartWidth)
  125. {
  126. fHeight = (size.width / 200 );
  127. }
  128. int nHeight = ceil(fHeight);
  129. if (nHeight == 0)
  130. {
  131. nHeight = 1;
  132. }
  133. Size labelSize ;
  134. if (size.width < chartWidth)
  135. {
  136. labelSize = Size(size.width,nHeight*32);
  137. }
  138. else
  139. {
  140. labelSize = Size(chartWidth,nHeight);
  141. return labelSize;
  142. }
  143.  
  144. void ChartDemoScene::touchEvent(cocos2d::Ref *pSender,Widget::TouchEventType type)
  145. {
  146. switch (type) {
  147. case ui::Widget::TouchEventType::ENDED:
  148. {
  149. if(str.empty())
  150. {
  151. showAlertShow("输入内容不能为空");
  152. break;
  153. }
  154. log("str = %s",str.c_str());
  155. auto time = getcurrMonthTime().c_str();
  156. auto text = Text::create(time,30);
  157. text->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
  158. text->setColor(Color3B::BLACK);
  159. auto _timeLayout = Layout::create();
  160. _timeLayout->setSize(Size(_listView->getSize().width,60));
  161. _timeLayout->setLayoutType(cocos2d::ui::Layout::Type::RELATIVE);
  162. auto rp_time = RelativeLayoutParameter::create();
  163. rp_time->setAlign(cocos2d::ui::RelativeLayoutParameter::RelativeAlign::CENTER_IN_PARENT);
  164. text->setLayoutParameter(rp_time);
  165. _timeLayout->addChild(text);
  166. _listView->pushBackCustomItem(_timeLayout);
  167. if(count % 2)
  168. {
  169. count++;
  170. auto _lLayout = Layout::create();
  171. _lLayout->setSize(Size(_listView->getSize().width,80));
  172. _lLayout->setLayoutType(cocos2d::ui::Layout::Type::RELATIVE);
  173. auto _lHeader = ui::ImageView::create("logo_douban.png");
  174. _lHeader->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
  175. _lHeader->setScale(0.5);
  176. auto rp_l = RelativeLayoutParameter::create();
  177. rp_l->setMargin(Margin(10,0));
  178. rp_l->setRelativeName("head");
  179. rp_l->setAlign(cocos2d::ui::RelativeLayoutParameter::RelativeAlign::PARENT_LEFT_CENTER_VERTICAL);
  180. _lHeader->setLayoutParameter(rp_l);
  181. _lLayout->addChild(_lHeader);
  182. auto _lTextContent = TextField::create("",30);
  183. _lTextContent->ignoreContentAdaptWithSize(false);
  184. auto size = calculateFontSize(str.c_str());
  185. _lTextContent->setSize(size);
  186. _lTextContent->setTextHorizontalAlignment(cocos2d::TextHAlignment::LEFT);
  187.  
  188. if(size.width < chartWidth)
  189. {
  190. _lTextContent->setTextHorizontalAlignment(cocos2d::TextHAlignment::RIGHT);
  191. }
  192. _lTextContent->setTextVerticalAlignment(cocos2d::TextVAlignment::CENTER);
  193. _lTextContent->setTouchEnabled(false);
  194. _lTextContent->setTag(T_Tag);
  195. _lTextContent->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
  196. _lTextContent->setColor(Color3B::BLACK);
  197. _lTextContent->setText(str);
  198. _lLayout->addChild(_lTextContent);
  199. str.clear();
  200. auto rp_t = RelativeLayoutParameter::create();
  201. rp_t->setMargin(Margin(10,0));
  202. rp_t->setRelativeToWidgetName("head");
  203. rp_t->setAlign(cocos2d::ui::RelativeLayoutParameter::RelativeAlign::LOCATION_RIGHT_OF_CENTER);
  204. _lTextContent->setLayoutParameter(rp_t);
  205. _listView->pushBackCustomItem(_lLayout);
  206. }else
  207. {
  208. count++;
  209. auto _rLayout = Layout::create();
  210. _rLayout->setSize(Size(_listView->getSize().width,80));
  211. _rLayout->setLayoutType(cocos2d::ui::Layout::Type::RELATIVE);
  212. auto _rHeader = ui::ImageView::create("logo_mingdao.png");
  213. _rHeader->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
  214. _rHeader->setScale(0.5);
  215. auto rp_r = RelativeLayoutParameter::create();
  216. rp_r->setMargin(Margin(0,10,0));
  217. rp_r->setRelativeName("head");
  218. rp_r->setAlign(cocos2d::ui::RelativeLayoutParameter::RelativeAlign::PARENT_RIGHT_CENTER_VERTICAL);
  219. _rHeader->setLayoutParameter(rp_r);
  220. _rLayout->addChild(_rHeader);
  221.  
  222. auto _rTextContent = TextField::create("",30);
  223. _rTextContent->setTag(T_Tag);
  224. _rTextContent->ignoreContentAdaptWithSize(false);
  225. auto size = calculateFontSize(str.c_str());
  226. _rTextContent->setSize(size);
  227. _rTextContent->setTextHorizontalAlignment(cocos2d::TextHAlignment::LEFT);
  228. _rTextContent->setTextVerticalAlignment(cocos2d::TextVAlignment::CENTER);
  229. _rTextContent->setTouchEnabled(false);
  230. _rTextContent->setAnchorPoint(Vec2::ANCHOR_MIDDLE_RIGHT);
  231. _rTextContent->setColor(Color3B::BLACK);
  232. _rTextContent->setText(str);
  233. str.clear();
  234. auto rp_l = RelativeLayoutParameter::create();
  235. rp_l->setMargin(Margin(0,0));
  236. rp_l->setRelativeToWidgetName("head");
  237. rp_l->setAlign(cocos2d::ui::RelativeLayoutParameter::RelativeAlign::LOCATION_LEFT_OF_CENTER);
  238. _rTextContent->setLayoutParameter(rp_l);
  239. _rLayout->addChild(_rTextContent);
  240. _listView->pushBackCustomItem(_rLayout);
  241. }
  242.  
  243. // if(_listView->getContentSize().height > _listView->getSize().height)
  244. // {
  245. _listView->scrollToBottom(0.5,true);
  246. // }
  247. editText->setText("");
  248. if(count > 3 )
  249. {
  250. _listView->removeItem(0);//删除时间标签,此时Item(0)就是内容标签
  251. auto temp = static_cast<Layout*>(_listView->getItem(0));//获取当前内容标签
  252. if(_text)
  253. {
  254. removeChild(_text);
  255. }
  256. _text = static_cast<TextField*>(temp->getChildByTag(T_Tag));//获取内容标签
  257. log("string = %s",_text->getStringValue().c_str());//获取内容
  258. log("file_path = %s",file_path.c_str());
  259. FILE* fp = std::fopen(file_path.c_str(),"at+");
  260. CCASSERT(fp != NULL,"file open error");
  261. length = _text->getStringValue().length();
  262. log("length = %lu",length);
  263. fwrite(_text->getStringValue().c_str(),length,1,fp);
  264. fclose(fp);
  265. _listView->removeItem(0);
  266. }
  267.  
  268. break;
  269. }
  270. default:
  271. break;
  272. }
  273. }
  274.  
  275. void ChartDemoScene::textFieldEvent(cocos2d::Ref *pSender,TextField::EventType type)
  276. {
  277. switch (type)
  278. {
  279. case TextField::EventType::ATTACH_WITH_IME:
  280. {
  281. TextField* textField = dynamic_cast<TextField*>(pSender);
  282. Size widgetSize = winSize;
  283. runAction(CCMoveTo::create(0.225f,Vec2(0,widgetSize.height / 2.0f)));
  284. textField->setTextHorizontalAlignment(TextHAlignment::LEFT);
  285. textField->setTextVerticalAlignment(TextVAlignment::TOP);
  286. }
  287. break;
  288. case TextField::EventType::DETACH_WITH_IME:
  289. {
  290. TextField* textField = dynamic_cast<TextField*>(pSender);
  291. Size widgetSize = winSize;
  292. runAction(CCMoveTo::create(0.175f,0)));
  293. textField->setTextHorizontalAlignment(TextHAlignment::LEFT);
  294. textField->setTextVerticalAlignment(TextVAlignment::CENTER);
  295. str = editText->getStringValue().c_str();
  296. str += "\n";
  297. }
  298. break;
  299. case TextField::EventType::INSERT_TEXT:
  300. break;
  301. case TextField::EventType::DELETE_BACKWARD:
  302. break;
  303. default:
  304. break;
  305. }
  306.  
  307. }
  308.  
  309. void ChartDemoScene::showAlertShow(std::string contentString)
  310. {
  311. auto alert = dynamic_cast<ui::Text*>(getChildByTag(Alert_Tag));
  312. if (alert->getUserData() == "11") {
  313. alert->setOpacity(255);
  314. char* userdata = "110";
  315. alert->setUserData(userdata);
  316. alert->setString(contentString);
  317. auto call_func = CallFunc::create(CC_CALLBACK_0(ChartDemoScene::alertCallback,this,alert));
  318. auto seq = Sequence::create(FadeOut::create(1.0f),call_func,NULL);
  319. alert->runAction(seq);
  320. }
  321. }
  322.  
  323. void ChartDemoScene::alertCallback(ui::Text* alert)
  324. {
  325. alert->setString("");
  326. char* userdata = "11";
  327. alert->setUserData(userdata);
  328. }
  329.  
  330. std::string ChartDemoScene::getcurrTime()//获取当前年月日
  331. {
  332. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
  333. struct timeval now;
  334. struct tm* time;
  335. gettimeofday(&now,NULL);
  336. time = localtime(&now.tv_sec);
  337. int year = time->tm_year + 1900;
  338. char date[32] = {0};
  339. sprintf(date,"%d-%02d-%02d",(int)time->tm_year + 1900,(int)time->tm_mon + 1,(int)time->tm_mday);
  340. return StringUtils::format("%s",date);
  341. #endif
  342. #if ( CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 )
  343. struct tm* tm;
  344. time_t timep;
  345. time(timep);
  346. tm = localtime(&timep);
  347. char date[32] = {0};
  348. sprintf(date,date);
  349. #endif
  350. }
  351.  
  352. std::string ChartDemoScene::getcurrMonthTime()
  353. {
  354. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
  355. struct timeval now;
  356. struct tm* time;
  357. gettimeofday(&now,NULL);
  358. time = localtime(&now.tv_sec);
  359. int year = time->tm_year + 1900;
  360. log("year = %d",year);
  361. char date1[24] = {0};
  362. char date[8] = {0};
  363. sprintf(date1,"%d:%02d:%02d:%02d:%02d:%02d",(int)time->tm_mday,time->tm_hour,time->tm_min,time->tm_sec);
  364. sprintf(date,"%02d:%02d",time->tm_min);
  365. return StringUtils::format("%s",date);
  366. #endif
  367. }
  368.  
  369.  
  370. void ChartDemoScene::menuCloseCallback(Ref* pSender)
  371. {
  372. #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
  373. MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
  374. return;
  375. #endif
  376. Director::getInstance()->end();
  377. #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
  378. exit(0);
  379. #endif
  380. }

猜你在找的Cocos2d-x相关文章