CCLabelTextFormatter.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. /****************************************************************************
  2. Copyright (c) 2013 Zynga Inc.
  3. Copyright (c) 2013-2017 Chukong Technologies Inc.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "2d/CCLabel.h"
  22. #include <vector>
  23. #include "base/ccUTF8.h"
  24. #include "base/CCDirector.h"
  25. #include "2d/CCFontAtlas.h"
  26. #include "2d/CCFontFNT.h"
  27. NS_CC_BEGIN
  28. void Label::computeAlignmentOffset()
  29. {
  30. _linesOffsetX.clear();
  31. switch (_hAlignment)
  32. {
  33. case cocos2d::TextHAlignment::LEFT:
  34. _linesOffsetX.assign(_numberOfLines, 0);
  35. break;
  36. case cocos2d::TextHAlignment::CENTER:
  37. for (auto lineWidth : _linesWidth)
  38. {
  39. _linesOffsetX.push_back((_contentSize.width - lineWidth) / 2.f);
  40. }
  41. break;
  42. case cocos2d::TextHAlignment::RIGHT:
  43. for (auto lineWidth : _linesWidth)
  44. {
  45. _linesOffsetX.push_back(_contentSize.width - lineWidth);
  46. }
  47. break;
  48. default:
  49. break;
  50. }
  51. switch (_vAlignment)
  52. {
  53. case cocos2d::TextVAlignment::TOP:
  54. _letterOffsetY = _contentSize.height;
  55. break;
  56. case cocos2d::TextVAlignment::CENTER:
  57. _letterOffsetY = (_contentSize.height + _textDesiredHeight) / 2.f;
  58. break;
  59. case cocos2d::TextVAlignment::BOTTOM:
  60. _letterOffsetY = _textDesiredHeight;
  61. break;
  62. default:
  63. break;
  64. }
  65. }
  66. int Label::getFirstCharLen(const std::u32string& /*utf32Text*/, int /*startIndex*/, int /*textLen*/)
  67. {
  68. return 1;
  69. }
  70. int Label::getFirstWordLen(const std::u32string& utf32Text, int startIndex, int textLen)
  71. {
  72. auto character = utf32Text[startIndex];
  73. if (StringUtils::isCJKUnicode(character) || StringUtils::isUnicodeSpace(character) || character == (char32_t)TextFormatter::NewLine)
  74. {
  75. return 1;
  76. }
  77. int len = 1;
  78. FontLetterDefinition letterDef;
  79. if(!_fontAtlas->getLetterDefinitionForChar(character, letterDef)) {
  80. return len;
  81. }
  82. auto nextLetterX = letterDef.xAdvance * _bmfontScale + _additionalKerning;
  83. auto contentScaleFactor = CC_CONTENT_SCALE_FACTOR();
  84. for (int index = startIndex + 1; index < textLen; ++index)
  85. {
  86. character = utf32Text[index];
  87. if (!_fontAtlas->getLetterDefinitionForChar(character, letterDef))
  88. {
  89. break;
  90. }
  91. auto letterX = (nextLetterX + letterDef.offsetX * _bmfontScale) / contentScaleFactor;
  92. if (_maxLineWidth > 0.f && letterX + letterDef.width * _bmfontScale > _maxLineWidth
  93. && !StringUtils::isUnicodeSpace(character))
  94. {
  95. return len;
  96. }
  97. nextLetterX += letterDef.xAdvance * _bmfontScale + _additionalKerning;
  98. if (character == (char16_t)TextFormatter::NewLine
  99. || StringUtils::isUnicodeSpace(character)
  100. || StringUtils::isCJKUnicode(character))
  101. {
  102. break;
  103. }
  104. len++;
  105. }
  106. return len;
  107. }
  108. void Label::updateBMFontScale()
  109. {
  110. auto font = _fontAtlas->getFont();
  111. if (_currentLabelType == LabelType::BMFONT) {
  112. FontFNT *bmFont = (FontFNT*)font;
  113. float originalFontSize = bmFont->getOriginalFontSize();
  114. _bmfontScale = _bmFontSize * CC_CONTENT_SCALE_FACTOR() / originalFontSize;
  115. }else{
  116. _bmfontScale = 1.0f;
  117. }
  118. }
  119. bool Label::multilineTextWrap(const std::function<int(const std::u32string&, int, int)>& nextTokenLen)
  120. {
  121. int textLen = getStringLength();
  122. int lineIndex = 0;
  123. float nextTokenX = 0.f;
  124. float nextTokenY = 0.f;
  125. float longestLine = 0.f;
  126. float letterRight = 0.f;
  127. auto contentScaleFactor = CC_CONTENT_SCALE_FACTOR();
  128. float lineSpacing = _lineSpacing * contentScaleFactor;
  129. float highestY = 0.f;
  130. float lowestY = 0.f;
  131. FontLetterDefinition letterDef;
  132. Vec2 letterPosition;
  133. bool nextChangeSize = true;
  134. this->updateBMFontScale();
  135. for (int index = 0; index < textLen; )
  136. {
  137. auto character = _utf32Text[index];
  138. if (character == (char32_t)TextFormatter::NewLine)
  139. {
  140. _linesWidth.push_back(letterRight);
  141. letterRight = 0.f;
  142. lineIndex++;
  143. nextTokenX = 0.f;
  144. nextTokenY -= _lineHeight*_bmfontScale + lineSpacing;
  145. recordPlaceholderInfo(index, character);
  146. index++;
  147. continue;
  148. }
  149. auto tokenLen = nextTokenLen(_utf32Text, index, textLen);
  150. float tokenHighestY = highestY;
  151. float tokenLowestY = lowestY;
  152. float tokenRight = letterRight;
  153. float nextLetterX = nextTokenX;
  154. bool newLine = false;
  155. for (int tmp = 0; tmp < tokenLen;++tmp)
  156. {
  157. int letterIndex = index + tmp;
  158. character = _utf32Text[letterIndex];
  159. if (character == (char16_t)TextFormatter::CarriageReturn)
  160. {
  161. recordPlaceholderInfo(letterIndex, character);
  162. continue;
  163. }
  164. // \b - Next char not change x position
  165. if (character == (char16_t)TextFormatter::NextCharNoChangeX)
  166. {
  167. nextChangeSize = false;
  168. recordPlaceholderInfo(letterIndex, character);
  169. continue;
  170. }
  171. if (!_fontAtlas->getLetterDefinitionForChar(character, letterDef))
  172. {
  173. recordPlaceholderInfo(letterIndex, character);
  174. CCLOG("LabelTextFormatter error:can't find letter definition in font file for letter: %c", character);
  175. continue;
  176. }
  177. auto letterX = (nextLetterX + letterDef.offsetX * _bmfontScale) / contentScaleFactor;
  178. if (_enableWrap && _maxLineWidth > 0.f && nextTokenX > 0.f && letterX + letterDef.width * _bmfontScale > _maxLineWidth
  179. && !StringUtils::isUnicodeSpace(character) && nextChangeSize)
  180. {
  181. _linesWidth.push_back(letterRight);
  182. letterRight = 0.f;
  183. lineIndex++;
  184. nextTokenX = 0.f;
  185. nextTokenY -= (_lineHeight*_bmfontScale + lineSpacing);
  186. newLine = true;
  187. break;
  188. }
  189. else
  190. {
  191. letterPosition.x = letterX;
  192. }
  193. letterPosition.y = (nextTokenY - letterDef.offsetY * _bmfontScale) / contentScaleFactor;
  194. recordLetterInfo(letterPosition, character, letterIndex, lineIndex);
  195. if (nextChangeSize)
  196. {
  197. if (_horizontalKernings && letterIndex < textLen - 1)
  198. nextLetterX += _horizontalKernings[letterIndex + 1];
  199. nextLetterX += letterDef.xAdvance * _bmfontScale + _additionalKerning;
  200. tokenRight = nextLetterX / contentScaleFactor;
  201. }
  202. nextChangeSize = true;
  203. if (tokenHighestY < letterPosition.y)
  204. tokenHighestY = letterPosition.y;
  205. if (tokenLowestY > letterPosition.y - letterDef.height * _bmfontScale)
  206. tokenLowestY = letterPosition.y - letterDef.height * _bmfontScale;
  207. }
  208. if (newLine)
  209. {
  210. continue;
  211. }
  212. nextTokenX = nextLetterX;
  213. letterRight = tokenRight;
  214. if (highestY < tokenHighestY)
  215. highestY = tokenHighestY;
  216. if (lowestY > tokenLowestY)
  217. lowestY = tokenLowestY;
  218. if (longestLine < letterRight)
  219. longestLine = letterRight;
  220. index += tokenLen;
  221. }
  222. _linesWidth.push_back(letterRight);
  223. _numberOfLines = lineIndex + 1;
  224. _textDesiredHeight = (_numberOfLines * _lineHeight * _bmfontScale) / contentScaleFactor;
  225. if (_numberOfLines > 1)
  226. _textDesiredHeight += (_numberOfLines - 1) * _lineSpacing;
  227. Size contentSize(_labelWidth, _labelHeight);
  228. if (_labelWidth <= 0.f)
  229. contentSize.width = longestLine;
  230. if (_labelHeight <= 0.f)
  231. contentSize.height = _textDesiredHeight;
  232. setContentSize(contentSize);
  233. _tailoredTopY = contentSize.height;
  234. _tailoredBottomY = 0.f;
  235. if (highestY > 0.f)
  236. _tailoredTopY = contentSize.height + highestY;
  237. if (lowestY < -_textDesiredHeight)
  238. _tailoredBottomY = _textDesiredHeight + lowestY;
  239. return true;
  240. }
  241. bool Label::multilineTextWrapByWord()
  242. {
  243. return multilineTextWrap(CC_CALLBACK_3(Label::getFirstWordLen, this));
  244. }
  245. bool Label::multilineTextWrapByChar()
  246. {
  247. return multilineTextWrap(CC_CALLBACK_3(Label::getFirstCharLen, this));
  248. }
  249. bool Label::isVerticalClamp()
  250. {
  251. if (_textDesiredHeight > _contentSize.height)
  252. {
  253. return true;
  254. }
  255. else
  256. {
  257. return false;
  258. }
  259. }
  260. bool Label::isHorizontalClamp()
  261. {
  262. bool letterClamp = false;
  263. for (int ctr = 0; ctr < _lengthOfString; ++ctr)
  264. {
  265. if (_lettersInfo[ctr].valid)
  266. {
  267. auto& letterDef = _fontAtlas->_letterDefinitions[_lettersInfo[ctr].utf32Char];
  268. auto px = _lettersInfo[ctr].positionX + letterDef.width/2 * _bmfontScale;
  269. auto lineIndex = _lettersInfo[ctr].lineIndex;
  270. if(_labelWidth > 0.f){
  271. if(!this->_enableWrap){
  272. if (px > _contentSize.width) {
  273. letterClamp = true;
  274. break;
  275. }
  276. }
  277. else{
  278. auto wordWidth = this->_linesWidth[lineIndex];
  279. if(wordWidth > this->_contentSize.width && (px > _contentSize.width)){
  280. letterClamp = true;
  281. break;
  282. }
  283. }
  284. }
  285. }
  286. }
  287. return letterClamp;
  288. }
  289. void Label::shrinkLabelToContentSize(const std::function<bool(void)>& lambda)
  290. {
  291. float fontSize = this->getRenderingFontSize();
  292. int i = 0;
  293. auto letterDefinition = _fontAtlas->_letterDefinitions;
  294. auto tempLetterDefinition = letterDefinition;
  295. float originalLineHeight = _lineHeight;
  296. bool flag = true;
  297. while (lambda()) {
  298. ++i;
  299. float newFontSize = fontSize - i;
  300. flag = false;
  301. if (newFontSize <= 0) {
  302. break;
  303. }
  304. float scale = newFontSize / fontSize;
  305. std::swap(_fontAtlas->_letterDefinitions, tempLetterDefinition);
  306. _fontAtlas->scaleFontLetterDefinition(scale);
  307. this->setLineHeight(originalLineHeight * scale);
  308. if (_maxLineWidth > 0.f && !_lineBreakWithoutSpaces)
  309. {
  310. multilineTextWrapByWord();
  311. }
  312. else
  313. {
  314. multilineTextWrapByChar();
  315. }
  316. computeAlignmentOffset();
  317. tempLetterDefinition = letterDefinition;
  318. }
  319. this->setLineHeight(originalLineHeight);
  320. std::swap(_fontAtlas->_letterDefinitions, letterDefinition);
  321. if (!flag) {
  322. if (fontSize - i >= 0) {
  323. this->scaleFontSizeDown(fontSize - i);
  324. }
  325. }
  326. }
  327. void Label::recordLetterInfo(const cocos2d::Vec2& point, char32_t utf32Char, int letterIndex, int lineIndex)
  328. {
  329. if (static_cast<std::size_t>(letterIndex) >= _lettersInfo.size())
  330. {
  331. LetterInfo tmpInfo;
  332. _lettersInfo.push_back(tmpInfo);
  333. }
  334. _lettersInfo[letterIndex].lineIndex = lineIndex;
  335. _lettersInfo[letterIndex].utf32Char = utf32Char;
  336. _lettersInfo[letterIndex].valid = _fontAtlas->_letterDefinitions[utf32Char].validDefinition;
  337. _lettersInfo[letterIndex].positionX = point.x;
  338. _lettersInfo[letterIndex].positionY = point.y;
  339. }
  340. void Label::recordPlaceholderInfo(int letterIndex, char32_t utf32Char)
  341. {
  342. if (static_cast<std::size_t>(letterIndex) >= _lettersInfo.size())
  343. {
  344. LetterInfo tmpInfo;
  345. _lettersInfo.push_back(tmpInfo);
  346. }
  347. _lettersInfo[letterIndex].utf32Char = utf32Char;
  348. _lettersInfo[letterIndex].valid = false;
  349. }
  350. NS_CC_END